﻿using Module_Debug.Hardware;
using RAD_GIR;
using Raydium;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.IO.Ports;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace Module_Debug.VDDIC_Gamma
{
    public partial class RM690B0_Gamma : Form
    {
        CaSDK CaSDKObj = new CaSDK();
        CRC16 CRCData = new CRC16();
        Gamma_Addr GAMMAs = new Gamma_Addr();
        CRAD_GIRW myRAD_IRC = new CRAD_GIRW();
        //Class_JOJO_gamma Flexible = new Class_JOJO_gamma();
        private bool Listening = false;//是否没有执行完invoke相关操作   
        private bool IClosing = false;//是否正在关闭串口，执行Application.DoEvents，并阻止再次invoke 

        private List<byte> buffer = new List<byte>(2048);//默认分配1/16页内存，并始终限制不允许超过
        private double R_x = 0.67;//
        private double R_y = 0.33;
        private double G_x = 0.22;
        private double G_y = 0.71;
        private double B_x = 0.14;
        private double B_y = 0.06;
        private double[,] D_lums;//目标值-单色
        private double[] D_lum;//目标值-白色
        private double D_x, D_y;
        private double lum_off, x_off, y_off;
        private int index = 0;
        private int flag1 = 1;
        private int flag2 = 1;
        private int flag3 = 1;
        private byte[] Send_buf = new byte[1];
        private byte[] Rec_tmp = new byte[1];
        private static bool Gamma_adjust_timeout_flag = false;
        private int Total_points;
        //功耗 IRC USE
        public double CASDK_LUM = 0.0, CASDK_x = 0.0, CASDK_y = 0.0, CASDK_JEITA_Flicker = 0.0;
        float ELVDD = 0, ELVSS = 0, ELVSSC = 0, VCI = 0, VCIC = 0, VDDIO = 0, VDDIOC = 0, AVDD = 0, AVDDC = 0;
        public float ELVDDC = 0;
        float VBAT = 0, VBATC = 0, DVDD = 0, DVDDC = 0;

        Byte IRC_WEIGHT_R = 0, IRC_WEIGHT_G = 0, IRC_WEIGHT_B = 0;
        double Ir, Ig, Ib;

        //IRC Gamma
        decimal[] RR = new decimal[10];
        decimal[] GG = new decimal[10];
        decimal[] BB = new decimal[10];

        //创建类型为Person的对象集合
        List<Setting.Gamma_Property> Diven_Gamma = new List<Setting.Gamma_Property>();
        List<Setting.Offset_Property> Diven_Offset = new List<Setting.Offset_Property>();

        //RM690B0 监听挂载
        frmMain frmHelp = null;

        public RM690B0_Gamma(frmMain RM690B0)
        {
            frmHelp = RM690B0;
            InitializeComponent();
            tbWidth.Text = frmHelp.HACT.Value.ToString();
            tbHeight.Text = frmHelp.VACT.Value.ToString();
            frmHelp.Child_window_hide_already = true;
            frmHelp.Child_Gamma_Window_Open_Enable = false;//防止重复开启子窗体   
        }
        private void RM690B0_Gamma_FormClosed(object sender, FormClosedEventArgs e)
        {
            frmHelp.comPort.DataReceived -= new SerialDataReceivedEventHandler(RM690B0_DataReceived);
            frmHelp.comPort.DataReceived += new SerialDataReceivedEventHandler(frmHelp.SerialPort1_DataReceived);
            frmHelp.Child_window_hide_already = false;
            frmHelp.Child_Gamma_Window_Open_Enable = true; //允许其他子窗体打开
            frmHelp.textBox1.Text = frmHelp.textBox1.Text + "RM690B0_Gamma_FormClosed！\r\n";
            frmHelp.IC_comboBox.Enabled = true;
        }
        private void RM690B0_Gamma_VisibleChanged(object sender, EventArgs e)
        {
            if (frmHelp.Child_window_hide_already == false) //子窗体已开启标识
            {
                frmHelp.comPort.DataReceived -= new SerialDataReceivedEventHandler(RM690B0_DataReceived);
                frmHelp.comPort.DataReceived += new SerialDataReceivedEventHandler(frmHelp.SerialPort1_DataReceived);
                frmHelp.textBox1.Text = frmHelp.textBox1.Text + "RM690B0_Gamma_FormHide！\r\n";
                frmHelp.Child_window_hide_already = true; //子窗体已隐藏标识
            }
            else
            {
                frmHelp.comPort.DataReceived -= new SerialDataReceivedEventHandler(frmHelp.SerialPort1_DataReceived);
                frmHelp.comPort.DataReceived += new SerialDataReceivedEventHandler(RM690B0_DataReceived);
                frmHelp.textBox1.Text = frmHelp.textBox1.Text + "RM690B0_Gamma_FormOpened！\r\n";
                frmHelp.Child_window_hide_already = false; //子窗体已开启标识
                Rbt_RM690B0_P15_CheckedChanged(null, null);
            }
        }
        public struct GIR_TuneParam
        {
            public string strIC_ID;     // IC ID
            public string strPanelShape;    // shape of panel
            public int nPanelWidth;         // panel width
            public int nPanelHeight;        // panel height
            public double dTargetLux;       // Target lux
            public double dCritRatio;       // criterion ratio of W and 50% W
            public double dRGBW_CritRatio;  // criterion ratio of rgb and W
        }
        GIR_TuneParam stGIR_TuneParam;
        private void GetTuneParam()

        {  // get the GIR tuning parameters

            stGIR_TuneParam.strIC_ID = cbICID.Text;
            stGIR_TuneParam.strPanelShape = cbShape.Text;
            stGIR_TuneParam.nPanelWidth = Convert.ToInt32(tbWidth.Text);
            stGIR_TuneParam.nPanelHeight = Convert.ToInt32(tbHeight.Text);
            stGIR_TuneParam.dTargetLux = Convert.ToDouble(tbTargetLux.Text);
            stGIR_TuneParam.dCritRatio = Convert.ToDouble(tbW_CritRatio.Text);
            stGIR_TuneParam.dRGBW_CritRatio = Convert.ToDouble(tbRGBW_CritRatio.Text);
        }
        public struct ST_REG_STRING
        {
            public string strRegH;
            public string strDataH;
            public string strRegL;
            public string strDataL;
        };
        public enum COLOR_INDEX
        {
            COLOR_R = 0,
            COLOR_G,
            COLOR_B,
            COLOR_W
        };

        private void RM690B0_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)//Getting data from Comm Port
        {
            if (IClosing) return;
            try
            {
                Listening = true;//设置标记，说明我已经开始处理数据，一会儿要使用系统UI的。         
                int n = frmHelp.comPort.BytesToRead;
                byte[] buf = new byte[n];
                byte data;

                frmHelp.comPort.Read(buf, 0, n);//读取缓冲数据     
                bool data_1_catched = false;//缓存记录数据是否捕获到    
                buffer.AddRange(buf);
                byte CRCH, CRCL;
                if (buffer.Count > 3)
                {
                    // 0x70: RM690B0的Gamma读写、寄存器读写、OTP读写    设置  返回
                    if ((buffer[0] == 0x76 || buffer[0] == 0x9E || buffer[0] == 0x99) && Setting.TempRecord.cmdLen > 0)
                    {
                        if (buffer.Count >= Setting.TempRecord.cmdLen)
                        {
                            Rec_tmp = new byte[Setting.TempRecord.cmdLen];
                            byte[] crcTemp = new byte[Setting.TempRecord.cmdLen];
                            buffer.CopyTo(0, crcTemp, 0, Setting.TempRecord.cmdLen);

                            CRCData.CalculateCrc16(crcTemp, out CRCH, out CRCL);
                            if (buffer[Setting.TempRecord.cmdLen - 2] != CRCH && buffer[Setting.TempRecord.cmdLen - 1] != CRCL)     //CRC校验出错
                            {
                                buffer.RemoveRange(0, buffer.Count);
                            }
                            else
                            {
                                buffer.CopyTo(0, Rec_tmp, 0, Setting.TempRecord.cmdLen);//复制一条完整数据到具体的数据缓存   
                                data_1_catched = true;
                                buffer.RemoveRange(0, Setting.TempRecord.cmdLen);//正确分析一条数据，从缓存中移除数据。 
                            }
                        }
                    }
                    else
                    {
                        buffer.RemoveRange(0, buffer.Count);
                    }
                }
                if (data_1_catched)
                {
                    this.Invoke((EventHandler)(delegate
                    {
                        List<NumericUpDown> R_Value = new List<NumericUpDown> { RM690B_R0, RM690B_R1, RM690B_R2, RM690B_R3, RM690B_R4, RM690B_R5, RM690B_R6, RM690B_R7, RM690B_R8, RM690B_R9, RM690B_R10, RM690B_R11, RM690B_R12, RM690B_R13, RM690B_R14, RM690B_R15, RM690B_R16, RM690B_R17, RM690B_R18, RM690B_R19, RM690B_R20, RM690B_R21, RM690B_R22, RM690B_R23, RM690B_R24, RM690B_R25, RM690B_R26 };
                        List<NumericUpDown> G_Value = new List<NumericUpDown> { RM690B_G0, RM690B_G1, RM690B_G2, RM690B_G3, RM690B_G4, RM690B_G5, RM690B_G6, RM690B_G7, RM690B_G8, RM690B_G9, RM690B_G10, RM690B_G11, RM690B_G12, RM690B_G13, RM690B_G14, RM690B_G15, RM690B_G16, RM690B_G17, RM690B_G18, RM690B_G19, RM690B_G20, RM690B_G21, RM690B_G22, RM690B_G23, RM690B_G24, RM690B_G25, RM690B_G26 };
                        List<NumericUpDown> B_Value = new List<NumericUpDown> { RM690B_B0, RM690B_B1, RM690B_B2, RM690B_B3, RM690B_B4, RM690B_B5, RM690B_B6, RM690B_B7, RM690B_B8, RM690B_B9, RM690B_B10, RM690B_B11, RM690B_B12, RM690B_B13, RM690B_B14, RM690B_B15, RM690B_B16, RM690B_B17, RM690B_B18, RM690B_B19, RM690B_B20, RM690B_B21, RM690B_B22, RM690B_B23, RM690B_B24, RM690B_B25, RM690B_B26 };

                        frmHelp.T1.Enabled = false; //停止超时计数
                        string str = "";                                               //华丽的分割线------------------------------
                        for (int b = 0; b < Setting.TempRecord.cmdLen; b++)
                        {
                            str = str + Convert.ToString(Rec_tmp[b]) + ",";

                        }
                        System.Diagnostics.Debug.Print(str);
                        //---------------------------------------------------RM690B0---------------------------------------
                        if (Rec_tmp[0] == 0x76)      //RM690B0
                        {
                            switch (Rec_tmp[1])
                            {
                                case 0x01:
                                    {
                                        if (Rec_tmp[4] == 0x00)
                                            frmHelp.textBox1.Text = frmHelp.textBox1.Text + "写寄存器\tOK！\r\n";
                                    }
                                    break;
                                case 0x02:
                                    {

                                        string tmp = "";
                                        for (int i = 3; i < (Setting.TempRecord.cmdLen - 3); i++)
                                        {
                                            tmp = tmp + String.Format("{0:X2}", Rec_tmp[i]) + ",";
                                        }
                                        tmp = tmp + String.Format("{0:X2}", Rec_tmp[Setting.TempRecord.cmdLen - 3]);
                                        RM690B0_txtRegData.Text = tmp;
                                        frmHelp.textBox1.Text = frmHelp.textBox1.Text + "寄存器\t读 OK！\r\n";

                                    }
                                    break;
                                case 0x08:
                                    {
                                        if (Rec_tmp[4] == 0x00)
                                            frmHelp.textBox1.Text = frmHelp.textBox1.Text + "GAMMA \t写 OK！\r\n";
                                        else if (Rec_tmp[4] == 0x02)
                                            frmHelp.textBox1.Text = frmHelp.textBox1.Text + "GAMMA \t写 ERROR！\r\n";
                                    }
                                    break;
                                case 0x07:
                                    {
                                    }
                                    break;
                                case 0x04:
                                    {
                                        if ((Rec_tmp[3] & 0x10) == 0x10)    //27p
                                        {
                                            if ((Rec_tmp[3] & 0x0f) == 0x01)
                                            {
                                                for (int a = 0; a < 27; a++)
                                                {
                                                    R_Value[26 - a].Value = Decimal.Parse((Rec_tmp[5 + 2 * a] & 0x03).ToString()) * 256 + Decimal.Parse(Rec_tmp[6 + 2 * a].ToString());
                                                }
                                                frmHelp.textBox1.Text = frmHelp.textBox1.Text + "红 Gamma数据\t读 OK！\r\n";
                                            }
                                            else if ((Rec_tmp[3] & 0x0f) == 0x02)
                                            {
                                                for (int a = 0; a < 27; a++)
                                                {
                                                    G_Value[26 - a].Value = Decimal.Parse((Rec_tmp[5 + 2 * a] & 0x03).ToString()) * 256 + Decimal.Parse(Rec_tmp[6 + 2 * a].ToString());
                                                }
                                                frmHelp.textBox1.Text = frmHelp.textBox1.Text + "绿 Gamma数据\t读 OK！\r\n";
                                            }
                                            else if ((Rec_tmp[3] & 0x0f) == 0x03)
                                            {
                                                for (int a = 0; a < 27; a++)
                                                {
                                                    B_Value[26 - a].Value = Decimal.Parse((Rec_tmp[5 + 2 * a] & 0x03).ToString()) * 256 + Decimal.Parse(Rec_tmp[6 + 2 * a].ToString());
                                                }
                                                frmHelp.textBox1.Text = frmHelp.textBox1.Text + "蓝 Gamma数据\t读 OK！\r\n";
                                            }

                                        }
                                        else
                                        {
                                            if ((Rec_tmp[3] & 0x0f) == 0x01)
                                            {
                                                for (int a = 0; a < 13; a++)
                                                {
                                                    R_Value[26 - a].Value = Decimal.Parse((Rec_tmp[5 + 2 * a] & 0x03).ToString()) * 256 + Decimal.Parse(Rec_tmp[6 + 2 * a].ToString());
                                                }
                                                frmHelp.textBox1.Text = frmHelp.textBox1.Text + "红 Gamma数据_13P\t读 OK！\r\n";
                                            }
                                            else if ((Rec_tmp[3] & 0x0f) == 0x02)
                                            {
                                                for (int a = 0; a < 13; a++)
                                                {
                                                    G_Value[26 - a].Value = Decimal.Parse((Rec_tmp[5 + 2 * a] & 0x03).ToString()) * 256 + Decimal.Parse(Rec_tmp[6 + 2 * a].ToString());
                                                }
                                                frmHelp.textBox1.Text = frmHelp.textBox1.Text + "绿 Gamma数据_13P\t读 OK！\r\n";
                                            }
                                            else if ((Rec_tmp[3] & 0x0f) == 0x03)
                                            {
                                                for (int a = 0; a < 13; a++)
                                                {
                                                    B_Value[26 - a].Value = Decimal.Parse((Rec_tmp[5 + 2 * a] & 0x03).ToString()) * 256 + Decimal.Parse(Rec_tmp[6 + 2 * a].ToString());
                                                }
                                                frmHelp.textBox1.Text = frmHelp.textBox1.Text + "蓝 Gamma数据_13P\t读 OK！\r\n";
                                            }

                                        }
                                    }
                                    break;
                                case 0x0D:
                                    {
                                        if (Rec_tmp[3] == 0x00)
                                            frmHelp.textBox1.Text = frmHelp.textBox1.Text + "OTP \t写 OK！\r\n";
                                        else if (Rec_tmp[3] == 0x02)
                                            frmHelp.textBox1.Text = frmHelp.textBox1.Text + "OTP \t写 ERROR！\r\n";
                                    }
                                    break;
                                case 0x0A:
                                    {
                                        if (Rec_tmp[4] == 0x00)
                                            frmHelp.textBox1.Text = frmHelp.textBox1.Text + "GAMMA \t传输 OK！\r\n";
                                        else if (Rec_tmp[4] == 0x02)
                                            frmHelp.textBox1.Text = frmHelp.textBox1.Text + "GAMMA \t传输 ERROR！\r\n";
                                    }
                                    break;

                                case 0x20:
                                    {
                                        frmHelp.textBox1.Text = frmHelp.textBox1.Text + "flash ID: " + Rec_tmp[4].ToString("x") + "," + Rec_tmp[5].ToString("x") + "\r\n";
                                    }
                                    break;

                                case 0x21:
                                    {
                                        if (Rec_tmp[4] == 0x00)
                                            frmHelp.textBox1.Text = frmHelp.textBox1.Text + "Erase Flash Finished \t写 OK！\r\n";
                                        else if (Rec_tmp[4] == 0x02)
                                            frmHelp.textBox1.Text = frmHelp.textBox1.Text + "Erase Flash ERROR \t写 ERROR！\r\n";
                                    }
                                    break;

                                case 0x22:
                                    {
                                        frmHelp.textBox1.Text = frmHelp.textBox1.Text + "Flash IC Status: " + Rec_tmp[4].ToString("x") + "," + Rec_tmp[5].ToString("x") + "\r\n";
                                    }
                                    break;

                                case 0x23:
                                    {
                                        if (Rec_tmp[4] == 0x00)
                                            frmHelp.textBox1.Text = frmHelp.textBox1.Text + "Check Flash  \t写 OK！\r\n";
                                        else if (Rec_tmp[4] == 0x02)
                                            frmHelp.textBox1.Text = frmHelp.textBox1.Text + "Check Flash  \t写 ERROR！\r\n";
                                    }
                                    break;

                                case 0x24:
                                    {
                                        if (Rec_tmp[4] == 0x00)
                                            frmHelp.textBox1.Text = frmHelp.textBox1.Text + "Step Five  \t写 OK！\r\n";
                                        else if (Rec_tmp[4] == 0x02)
                                            frmHelp.textBox1.Text = frmHelp.textBox1.Text + "Step Five  \t写 ERROR！\r\n";
                                    }
                                    break;

                                case 0x25:
                                    {
                                        if (Rec_tmp[4] == 0x00)
                                            frmHelp.textBox1.Text = frmHelp.textBox1.Text + "OTP Five  \t写 OK！\r\n";
                                        else if (Rec_tmp[4] == 0x02)
                                            frmHelp.textBox1.Text = frmHelp.textBox1.Text + "OTP Five  \t写 ERROR！\r\n";
                                    }
                                    break;
                                case 0x26:
                                    {
                                        string tmp = null;
                                        Setting.TempRecord.cmdLen = 14;
                                        for (int i = 3; i < (Setting.TempRecord.cmdLen - 3); i++)
                                        {
                                            tmp = tmp + String.Format("{0:X2}", Rec_tmp[i]) + ",";
                                        }
                                        tmp = tmp + String.Format("{0:X2}", Rec_tmp[Setting.TempRecord.cmdLen - 3]);
                                        frmHelp.textBox1.Text = frmHelp.textBox1.Text + tmp + "\n ";

                                        frmHelp.textBox1.Text = frmHelp.textBox1.Text + "Check_Flash 完成！\r\n";
                                    }
                                    break;
                                case 0x27:
                                    {
                                        frmHelp.textBox1.Text = frmHelp.textBox1.Text + "Viewtrix Demura on  \t OK！\r\n";
                                    }
                                    break;
                                case 0x28:
                                    {
                                        frmHelp.textBox1.Text = frmHelp.textBox1.Text + "Viewtrix Demura off  \t OK！\r\n";
                                    }
                                    break;
                                default: break;

                            }
                        }
                        else if (Rec_tmp[0] == 0x9E)
                        {
                            switch (Rec_tmp[3])
                            {
                                case 0x00:
                                    {
                                        T1.Enabled = false;
                                        ELVDDC = (float)(BitConverter.ToUInt16(Rec_tmp, 6) * 2.5) / 120;
                                        ELVDDC = ELVDDC - (float)(0.6112 - 0.007674 * ELVDDC);
                                        ELVSS = (float)(BitConverter.ToUInt16(Rec_tmp, 28) * 0.00157); if (ELVSS < 0.05) { ELVSS = 0; }
                                        //ELVSSC = (float)(474.6 - (BitConverter.ToUInt16(Rec_tmp, 22) * 0.152));
                                        ELVSSC = ELVDDC;
                                        if (ELVDDC != 0)
                                        {
                                            Random rd = new Random();
                                            int a = rd.Next(-55, 55);
                                            float f = (float)(a * 0.001);
                                            ELVSSC = ELVSSC + f;
                                        }

                                    }
                                    break;
                            }
                        }
                        else if (Rec_tmp[0] == 0x99) //GENWR
                        {
                            switch (Rec_tmp[1])
                            {
                                case 0x02:
                                    {
                                        string tmp = "";                    //8bit  read
                                        {
                                            for (int i = 3; i <= (Rec_tmp[2] + 2); i++)
                                            {
                                                if (i == (Rec_tmp[2] + 2))
                                                {
                                                    tmp = tmp + String.Format("{0:X2}", Rec_tmp[i]);//16进制
                                                }
                                                else if (i == 3)
                                                {
                                                    if (Rec_tmp[3] == 0xB0)
                                                    {

                                                    }
                                                    tmp = tmp + String.Format("{0:X2}", Rec_tmp[i]) + ",";//16进制
                                                }
                                                else
                                                {
                                                    tmp = tmp + String.Format("{0:X2}", Rec_tmp[i]) + ",";//16进制
                                                }
                                            }
                                        }
                                        frmHelp.Generate_Read_Result_txt.AppendText(tmp + "\r\n");
                                        frmHelp.textBox1.Text = frmHelp.textBox1.Text + "[" + DateTime.Now.ToLongTimeString().ToString() + "]：" + "visionox 8bit寄存器--读 OK！\r\n";
                                        Application.DoEvents();
                                    }
                                    break;
                            }
                        }
                        frmHelp.textBox1.SelectionStart = this.frmHelp.textBox1.Text.Length;
                        frmHelp.textBox1.ScrollToCaret();//滚动到光标处
                        if (frmHelp.textBox1.Lines.Length > 50) frmHelp.textBox1.Text = null;
                    }));
                }
            }
            finally
            {
                Listening = false;
            }
        }
        string[] P27_Grey = new string[] { "0", "1", "3", "7", "11", "15", "19", "23", "27", "31", "35", "39", "47", "55", "63", "79", "95", "111", "127", "143", "159", "175", "191", "207", "223", "239", "255" };
        string[] P13_Grey = new string[] { "0", " 1", " 3", " 7", " 11", " 15", "31", " 63", "95", " 127", "159", "191", "255" };
        //Gamma保存
        private void RM690B0_SaveGamma_Click(object sender, EventArgs e)
        {
            List<NumericUpDown> R_Value = new List<NumericUpDown> { RM690B_R0, RM690B_R1, RM690B_R2, RM690B_R3, RM690B_R4, RM690B_R5, RM690B_R6, RM690B_R7, RM690B_R8, RM690B_R9, RM690B_R10, RM690B_R11, RM690B_R12, RM690B_R13, RM690B_R14, RM690B_R15, RM690B_R16, RM690B_R17, RM690B_R18, RM690B_R19, RM690B_R20, RM690B_R21, RM690B_R22, RM690B_R23, RM690B_R24, RM690B_R25, RM690B_R26 };
            List<NumericUpDown> G_Value = new List<NumericUpDown> { RM690B_G0, RM690B_G1, RM690B_G2, RM690B_G3, RM690B_G4, RM690B_G5, RM690B_G6, RM690B_G7, RM690B_G8, RM690B_G9, RM690B_G10, RM690B_G11, RM690B_G12, RM690B_G13, RM690B_G14, RM690B_G15, RM690B_G16, RM690B_G17, RM690B_G18, RM690B_G19, RM690B_G20, RM690B_G21, RM690B_G22, RM690B_G23, RM690B_G24, RM690B_G25, RM690B_G26 };
            List<NumericUpDown> B_Value = new List<NumericUpDown> { RM690B_B0, RM690B_B1, RM690B_B2, RM690B_B3, RM690B_B4, RM690B_B5, RM690B_B6, RM690B_B7, RM690B_B8, RM690B_B9, RM690B_B10, RM690B_B11, RM690B_B12, RM690B_B13, RM690B_B14, RM690B_B15, RM690B_B16, RM690B_B17, RM690B_B18, RM690B_B19, RM690B_B20, RM690B_B21, RM690B_B22, RM690B_B23, RM690B_B24, RM690B_B25, RM690B_B26 };

            SaveFileDialog sf = new SaveFileDialog(); //对话框
            sf.Filter = @"csv文件(*.csv)|*.csv|所有文件(*.*)|*.*"; //定义保存的文件的类型
            string str = "保存Gamma文件";
            if (sf.ShowDialog() == DialogResult.OK) //如果确定保存
            {
                if (sf.FileName == "") return; //如果没有输入文件名
                try
                {
                    StreamWriter sw = null; //文件流
                    sw = new StreamWriter(sf.FileName, false, Encoding.UTF8);
                    for (int i = 0; i < 27; i++)
                    {
                        string temp = P27_Grey[i].ToString();
                        str = str + "R" + temp + "," + R_Value[26 - i].Text + "," + "G" + temp + "," + G_Value[26 - i].Text + "," + "B" + temp + "," + B_Value[26 - i].Text + "\r\n";
                    }
                    sw.WriteLine(str);
                    sw.Dispose(); //释放资源
                    sw.Close(); //关闭数据流
                    MessageBox.Show("Gamma保存OK！", "系统提示：");
                }
                catch
                {
                    MessageBox.Show("Gamma保存时发生错误，请再试！", "系统提示：");
                }
            }
        } //
        //Gamma载入
        private void RM690B0_LoadGamma_Click(object sender, EventArgs e)
        {
            OpenFileDialog of = new OpenFileDialog();
            string strtmp = "";
            of.Filter = @"csv文件(*.csv)|*.csv|所有文件(*.*)|*.*"; ;
            of.Title = "打开Gamma文件";

            if (of.ShowDialog() == DialogResult.OK)
            {
                //读取文本信息
                FileStream fs = new FileStream(of.FileName, FileMode.Open, FileAccess.Read);
                StreamReader streamReader = new StreamReader(fs, Encoding.GetEncoding("GBK"));
                streamReader.BaseStream.Seek(0, SeekOrigin.Begin);
                string strLine = streamReader.ReadLine();
                //循环读取文本信息
                while (!string.IsNullOrEmpty(strLine))
                {
                    strtmp = strtmp + strLine + ",";
                    strLine = streamReader.ReadLine(); //循环读取下一行
                }
                fs.Close(); //关闭流
                streamReader.Close();
                string[] arrtmp = strtmp.Split(new Char[] { ',' });
                List<NumericUpDown> R_Value = new List<NumericUpDown> { RM690B_R0, RM690B_R1, RM690B_R2, RM690B_R3, RM690B_R4, RM690B_R5, RM690B_R6, RM690B_R7, RM690B_R8, RM690B_R9, RM690B_R10, RM690B_R11, RM690B_R12, RM690B_R13, RM690B_R14, RM690B_R15, RM690B_R16, RM690B_R17, RM690B_R18, RM690B_R19, RM690B_R20, RM690B_R21, RM690B_R22, RM690B_R23, RM690B_R24, RM690B_R25, RM690B_R26 };
                List<NumericUpDown> G_Value = new List<NumericUpDown> { RM690B_G0, RM690B_G1, RM690B_G2, RM690B_G3, RM690B_G4, RM690B_G5, RM690B_G6, RM690B_G7, RM690B_G8, RM690B_G9, RM690B_G10, RM690B_G11, RM690B_G12, RM690B_G13, RM690B_G14, RM690B_G15, RM690B_G16, RM690B_G17, RM690B_G18, RM690B_G19, RM690B_G20, RM690B_G21, RM690B_G22, RM690B_G23, RM690B_G24, RM690B_G25, RM690B_G26 };
                List<NumericUpDown> B_Value = new List<NumericUpDown> { RM690B_B0, RM690B_B1, RM690B_B2, RM690B_B3, RM690B_B4, RM690B_B5, RM690B_B6, RM690B_B7, RM690B_B8, RM690B_B9, RM690B_B10, RM690B_B11, RM690B_B12, RM690B_B13, RM690B_B14, RM690B_B15, RM690B_B16, RM690B_B17, RM690B_B18, RM690B_B19, RM690B_B20, RM690B_B21, RM690B_B22, RM690B_B23, RM690B_B24, RM690B_B25, RM690B_B26 };
                for (int i = 0; i < 27; i++)
                {
                    R_Value[26 - i].Text = arrtmp[6 * i + 1].ToString();
                    G_Value[26 - i].Text = arrtmp[6 * i + 3].ToString();
                    B_Value[26 - i].Text = arrtmp[6 * i + 5].ToString();
                }
            }
        }
        public void RM690B0_GAMMA_Click(object sender, EventArgs e)
        {
            List<NumericUpDown> R_Value = new List<NumericUpDown> { RM690B_R0, RM690B_R1, RM690B_R2, RM690B_R3, RM690B_R4, RM690B_R5, RM690B_R6, RM690B_R7, RM690B_R8, RM690B_R9, RM690B_R10, RM690B_R11, RM690B_R12, RM690B_R13, RM690B_R14, RM690B_R15, RM690B_R16, RM690B_R17, RM690B_R18, RM690B_R19, RM690B_R20, RM690B_R21, RM690B_R22, RM690B_R23, RM690B_R24, RM690B_R25, RM690B_R26 };
            List<NumericUpDown> G_Value = new List<NumericUpDown> { RM690B_G0, RM690B_G1, RM690B_G2, RM690B_G3, RM690B_G4, RM690B_G5, RM690B_G6, RM690B_G7, RM690B_G8, RM690B_G9, RM690B_G10, RM690B_G11, RM690B_G12, RM690B_G13, RM690B_G14, RM690B_G15, RM690B_G16, RM690B_G17, RM690B_G18, RM690B_G19, RM690B_G20, RM690B_G21, RM690B_G22, RM690B_G23, RM690B_G24, RM690B_G25, RM690B_G26 };
            List<NumericUpDown> B_Value = new List<NumericUpDown> { RM690B_B0, RM690B_B1, RM690B_B2, RM690B_B3, RM690B_B4, RM690B_B5, RM690B_B6, RM690B_B7, RM690B_B8, RM690B_B9, RM690B_B10, RM690B_B11, RM690B_B12, RM690B_B13, RM690B_B14, RM690B_B15, RM690B_B16, RM690B_B17, RM690B_B18, RM690B_B19, RM690B_B20, RM690B_B21, RM690B_B22, RM690B_B23, RM690B_B24, RM690B_B25, RM690B_B26 };

            Button btnTmp = (Button)sender;
            if (rbt_RM690B0_P27.Checked)
            {
                Send_buf = new byte[61];
            }
            else
            {
                Send_buf = new byte[33];
            }
            Send_buf[0] = 0x76; //RM690B0
            if (Gamma1.Checked)
            {
                Send_buf[4] = 0x01;
            }
            else if (Gamma2.Checked)
            {
                Send_buf[4] = 0x02;
            }
            else if (Gamma3.Checked)
            {
                Send_buf[4] = 0x03;
            }
            else if (Gamma4.Checked)
            {
                Send_buf[4] = 0x04;
            }
            else if (Gamma5.Checked)
            {
                Send_buf[4] = 0x05;
            }
            switch (btnTmp.Name)
            {
                case "RM690B0_GammaR_Red":
                    {
                        if (rbt_RM690B0_P27.Checked)
                        {
                            Send_buf[1] = 0x04;
                            Send_buf[2] = 56;//读Gamma
                            Setting.TempRecord.cmdLen = 61;
                            Send_buf[3] = 0x11;                            //红色red
                        }
                        else
                        {
                            Send_buf[1] = 0x04;
                            Send_buf[2] = 28;//读Gamma
                            Send_buf[3] = 0x01;
                            Setting.TempRecord.cmdLen = 33;
                        }
                    }
                    break;
                case "RM690B0_GammaR_Green":
                    {
                        if (rbt_RM690B0_P27.Checked)
                        {
                            Send_buf[1] = 0x04;
                            Send_buf[2] = 56;//读Gamma
                            Send_buf[3] = 0x12;
                            Setting.TempRecord.cmdLen = 61;//红色red
                        }
                        else
                        {
                            Send_buf[1] = 0x04;
                            Send_buf[2] = 28;//读Gamma
                            Send_buf[3] = 0x02;
                            Setting.TempRecord.cmdLen = 33;
                        }                                     /// Setting.TempRecord.RM690B0mdType = 0x04;
                    }
                    break;
                case "RM690B0_GammaR_Blue":
                    {
                        if (rbt_RM690B0_P27.Checked)
                        {
                            Send_buf[1] = 0x04;
                            Send_buf[2] = 56;//读Gamma
                            Send_buf[3] = 0x13;
                            Setting.TempRecord.cmdLen = 61;//红色red
                        }
                        else
                        {
                            Send_buf[1] = 0x04;
                            Send_buf[2] = 28;//读Gamma
                            Send_buf[3] = 0x03;
                            Setting.TempRecord.cmdLen = 33;
                        }
                    }
                    break;
                case "RM690B0_GammaW_Red":
                    {
                        if (rbt_RM690B0_P27.Checked)
                        {
                            Send_buf[1] = 0x03;
                            Send_buf[2] = 56;
                            Send_buf[3] = 0x11;
                            for (int i = 0; i < 27; i++)
                            {
                                Send_buf[2 * i + 5] = Convert.ToByte(Convert.ToUInt16(R_Value[26 - i].Value.ToString()) >> 8);
                                Send_buf[2 * i + 6] = Convert.ToByte(Convert.ToUInt16(R_Value[26 - i].Value.ToString()) & 0xff);
                            }
                        }
                        else
                        {
                            Send_buf[1] = 0x03;
                            Send_buf[2] = 28;
                            Send_buf[3] = 0x01;
                            for (int i = 0; i < 13; i++)
                            {
                                Send_buf[2 * i + 5] = Convert.ToByte(Convert.ToUInt16(R_Value[26 - i].Value.ToString()) >> 8);
                                Send_buf[2 * i + 6] = Convert.ToByte(Convert.ToUInt16(R_Value[26 - i].Value.ToString()) & 0xff);
                            }
                        }

                    }
                    break;
                case "RM690B0_GammaW_Green":
                    {
                        if (rbt_RM690B0_P27.Checked)
                        {
                            Send_buf[1] = 0x03;
                            Send_buf[2] = 56;
                            Send_buf[3] = 0x12;
                            for (int i = 0; i < 27; i++)
                            {
                                Send_buf[2 * i + 5] = Convert.ToByte(Convert.ToUInt16(G_Value[26 - i].Value.ToString()) >> 8);
                                Send_buf[2 * i + 6] = Convert.ToByte(Convert.ToUInt16(G_Value[26 - i].Value.ToString()) & 0xff);
                            }
                        }
                        else
                        {
                            Send_buf[1] = 0x03;
                            Send_buf[2] = 28;
                            Send_buf[3] = 0x02;
                            for (int i = 0; i < 13; i++)
                            {
                                Send_buf[2 * i + 5] = Convert.ToByte(Convert.ToUInt16(G_Value[26 - i].Value.ToString()) >> 8);
                                Send_buf[2 * i + 6] = Convert.ToByte(Convert.ToUInt16(G_Value[26 - i].Value.ToString()) & 0xff);
                            }
                        }

                    }
                    break;
                case "RM690B0_GammaW_Blue":     //8
                    {
                        if (rbt_RM690B0_P27.Checked)
                        {
                            Send_buf[1] = 0x03;
                            Send_buf[2] = 56;
                            Send_buf[3] = 0x13;
                            for (int i = 0; i < 27; i++)
                            {
                                Send_buf[2 * i + 5] = Convert.ToByte(Convert.ToUInt16(B_Value[26 - i].Value.ToString()) >> 8);
                                Send_buf[2 * i + 6] = Convert.ToByte(Convert.ToUInt16(B_Value[26 - i].Value.ToString()) & 0xff);
                            }
                        }
                        else
                        {
                            Send_buf[1] = 0x03;
                            Send_buf[2] = 28;
                            Send_buf[3] = 0x03;
                            for (int i = 0; i < 13; i++)
                            {
                                Send_buf[2 * i + 5] = Convert.ToByte(Convert.ToUInt16(B_Value[26 - i].Value.ToString()) >> 8);
                                Send_buf[2 * i + 6] = Convert.ToByte(Convert.ToUInt16(B_Value[26 - i].Value.ToString()) & 0xff);
                            }
                        }
                    }
                    break;
                default:
                    break;
            }
            CRCData.CalculateCrc16(Send_buf, out Send_buf[Send_buf[2] + 3], out Send_buf[Send_buf[2] + 4]);
            try
            {
                frmHelp.comPort.Write(Send_buf, 0, Send_buf[2] + 5);   //RM690B0
            }
            catch
            {
                MessageBox.Show("串口有误，请检查", "错误");
            }
            frmHelp.T1.Enabled = false;
            frmHelp.T1.Interval = 2000;
            frmHelp.T1.Enabled = true;
        }



        public void RM690B0_Others_Click(object sender, EventArgs e)
        {
            Send_buf = new byte[7];
            Button btnTmp = (Button)sender;
            Setting.TempRecord.cmdLen = 7;

            Send_buf[0] = 0x70;
            Send_buf[2] = 0x02;

            switch (btnTmp.Name)
            {
                case "VT_OTP": //otp Gamma
                    {
                        //Send_buf[1] = 0x0D;
                        //if (rbt_otp_p0.Checked == true)
                        //{ Send_buf[3] = 0x0F; }
                        //else if (rbt_otp_p1.Checked == true)
                        //{ Send_buf[3] = 0x1B; }
                        //else if (rbt_otp_p2.Checked == true)
                        //{ Send_buf[3] = 0x1C; }

                        //else if (rbt_otp_all.Checked == true)
                        //{ Send_buf[3] = 0x0E; }
                        //else if (rbt_otp_gamma.Checked == true)
                        //{ Send_buf[3] = 0x0D; }
                    }
                    break;
                //--------------------------------------------------------------------
                case "Read_Flash_ID":         //读Flash ID
                    {
                        Send_buf[1] = 0x20;
                    }
                    break;
                case "Erase_Flash":         //擦除Flash
                    {
                        Send_buf[1] = 0x21;
                        // frmHelp.textBox1.Text = frmHelp.textBox1.Text + "Please Wait for 50 seconds\r\n";
                    }
                    break;
                case "Flash_Status":         //确认Flash Status
                    {
                        Send_buf[1] = 0x22;
                        //frmHelp.textBox1.Text = frmHelp.textBox1.Text + "Please Wait for 30 seconds\r\n";
                    }
                    break;
                case "Check_Flash":         //确认Flash Status
                    {
                        Send_buf[1] = 0x23;
                        //frmHelp.textBox1.Text = frmHelp.textBox1.Text + "Please Wait for 30 seconds\r\n";
                    }
                    break;
                case "Five_Step":         //确认Flash Status
                    {
                        Send_buf[1] = 0x24;
                        //frmHelp.textBox1.Text = frmHelp.textBox1.Text + "Please Wait for 30 seconds\r\n";
                    }
                    break;
                case "OTP_Flash":         //确认Flash Status
                    {
                        Send_buf[1] = 0x25;
                        frmHelp.textBox1.Text = frmHelp.textBox1.Text + "OTP Please Wait for 40 seconds\r\n";
                    }
                    break;
                case "CRC_check":
                    {
                        Send_buf[1] = 0x26;
                        frmHelp.textBox1.Text = frmHelp.textBox1.Text + "CRC_check\r\n";
                    }
                    break;
                case "Demura_on":
                    {
                        Send_buf[1] = 0x27;
                    }
                    break;
                case "Demura_off":
                    {
                        Send_buf[1] = 0x28;
                    }
                    break;
                default:
                    break;
            }
            CRCData.CalculateCrc16(Send_buf, out Send_buf[5], out Send_buf[6]);
            try
            {
                frmHelp.comPort.Write(Send_buf, 0, 7);
            }
            catch
            {
                MessageBox.Show("串口有误，请检查", "错误");
            }
            frmHelp.T1.Enabled = false;
            frmHelp.T1.Interval = 2000;
            frmHelp.T1.Enabled = true;
        }


        public void RM690B0_RegWR_Click(object sender, EventArgs e)
        {
            Button btnTmp = (Button)sender;
            Int32 DataNum;
            string strLine = Convert.ToString(RM690B0_txtRegData.Text);
            string[] arr = strLine.Split(','); //以逗号分割，添加到数组

            switch (btnTmp.Name)
            {
                case "RM690B0_RegW":
                    {
                        Setting.TempRecord.cmdLen = arr.Length + 5;
                        Send_buf = new byte[arr.Length + 5];
                        Send_buf[0] = 0x76;//RM690B0
                        Send_buf[1] = 0x01;
                        Send_buf[2] = byte.Parse(arr.Length.ToString());
                        for (int i = 0; i < arr.Length; i++)
                        {
                            Send_buf[3 + i] = byte.Parse((Convert.ToInt32(arr[i], 16)).ToString());
                        }
                        CRCData.CalculateCrc16(Send_buf, out Send_buf[5 + arr.Length - 2], out Send_buf[5 + arr.Length - 1]);
                        try
                        {
                            frmHelp.comPort.Write(Send_buf, 0, 5 + arr.Length);
                        }
                        catch
                        {
                            MessageBox.Show("串口有误，请检查", "错误");
                        }
                    }
                    break;
                case "RM690B0_RegR":
                    {
                        //  Setting.TempRecord.RM690B0mdType = 0x02;
                        try
                        {
                            DataNum = Convert.ToInt32(RM690B0_txtDataNum.Text) + 1;
                            Setting.TempRecord.cmdLen = DataNum + 5;
                            Send_buf = new byte[DataNum + 5];
                            Send_buf[0] = 0x76; //RM690B0
                            Send_buf[1] = 0x02;
                            Send_buf[2] = byte.Parse(Convert.ToString(DataNum));
                            Send_buf[3] = byte.Parse((Convert.ToInt32(arr[0], 16)).ToString());  //cmd
                            CRCData.CalculateCrc16(Send_buf, out Send_buf[5 + DataNum - 2], out Send_buf[5 + DataNum - 1]);
                        }
                        catch
                        {
                            MessageBox.Show("读取长度有误，请检查", "错误");
                            break;
                        }
                        try
                        {
                            frmHelp.comPort.Write(Send_buf, 0, 5 + DataNum);
                        }
                        catch
                        {
                            MessageBox.Show("串口有误，请检查", "错误");
                        }
                    }
                    break;
                default: break;
            }
            frmHelp.T1.Enabled = false;
            frmHelp.T1.Interval = 2000;
            frmHelp.T1.Enabled = true;
        }


        public void btnAutoGammas_RM690B0_Click(object sender, EventArgs e)
        {
            index = 0;
            flag1 = 1;
            flag2 = 1;
            flag3 = 1;
            frmHelp.numPatternR.Value = Diven_Offset[index].NO;
            frmHelp.numPatternG.Value = Diven_Offset[index].NO;
            frmHelp.numPatternB.Value = Diven_Offset[index].NO;
            Application.DoEvents();
            frmHelp.OLED_Show_Click(frmHelp.btnwhite, e);

            Thread.Sleep(500);
            T20.Enabled = true;
            T20.Interval = 300;
        }
        public void btnVTStop_Click(object sender, EventArgs e)
        {
            T20.Enabled = false;
            flag1 = 1;
            flag2 = 1;
            flag3 = 1;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            RM690B0_auto_gamma_write(0x3637, 900, 0x6f70, 900, 0xa6a7, 0);
        }
        public RAD_GIR.Raydium.IC_ID ic_id;     // IC ID for all cmds query.
        public RAD_GIR.Raydium.SHAPE sp;        // the panel shape for cmds query.
        private bool bInited;
        int PatType;    // pattren type
        string strIC_Name;      // IC Name, get via init()
        public bool Init()
        {
            bInited = false;
            switch (stGIR_TuneParam.strIC_ID)
            {
                case "RM690BX":
                    ic_id = RAD_GIR.Raydium.IC_ID.RM690BX;
                    break;

                case "RM6D03X":
                    ic_id = RAD_GIR.Raydium.IC_ID.RM6D03X;
                    break;
            }
            // init IC and get information
            if (!myRAD_IRC.GIR_IC_Init(ic_id, out strIC_Name))
            {
                MessageBox.Show("Can't find the matching IC.", "Error", MessageBoxButtons.OK);
                return false;
            }
            if (stGIR_TuneParam.strPanelShape == "Rectangle")
                sp = RAD_GIR.Raydium.SHAPE.SP_RECT;
            else
                sp = RAD_GIR.Raydium.SHAPE.SP_CIRCLE;
            bInited = true; // status of all initialization is done.
            return true;
        }
        private bool RunInit()
        {
            if (!Init()) // initialize GDP control
            {

                return false;
            }

            return true;
        }
        private void BTN_Init_Click(object sender, EventArgs e)
        {
            // Thread Thread_RunInit;
            // get the GIR tuning parameters
            GetTuneParam();
            //object value = null;
            //Thread_RunInit = new Thread(() => { value = RunInit(); });
            //Thread_RunInit.IsBackground = true;
            //Thread_RunInit.Start();
            RunInit();
        }
        private void DDIC_Reg_write(string str)
        {
            string[] strt = str.Split(',');
            byte[] Send_buf = new byte[strt.Length + 5];
            Send_buf[0] = 0x80;//RM692E1_667
            Send_buf[1] = 0x01;//RM692E1_667
            Send_buf[2] = (byte)strt.Length;
            Setting.TempRecord.cmdLen = Send_buf[2] + 5;

            if (str == "")
                return;
            else
            {
                try
                {
                    for (int i = 0; i < strt.Length; i++)
                    {
                        Send_buf[3 + i] = byte.Parse((Convert.ToInt32(strt[i], 16)).ToString());
                    }

                }
                catch
                {
                    MessageBox.Show("格式输入有误");
                }
                CRCData.CalculateCrc16(Send_buf, out Send_buf[strt.Length + 5 - 2], out Send_buf[strt.Length + 5 - 1]);
                try
                {
                    frmHelp.comPort.Write(Send_buf, 0, strt.Length + 5);
                }
                catch
                {
                    MessageBox.Show("串口有误，请检查", "错误");
                    return;
                }
            }
        }

        List<string> LstrRet = new List<string>();
        private void BTN_GetSetting_Click(object sender, EventArgs e)
        {

            txtLog.AppendText("\r\n");
            txtLog.AppendText("***** Set for GIR Offset 1 tuning *****\r\n");
            // get the initial setting commands
            LstrRet.Clear();
            if (!myRAD_IRC.GetCmdQueryInitSet(ic_id, sp, stGIR_TuneParam.nPanelWidth, stGIR_TuneParam.nPanelHeight, ref LstrRet))
            {
                MessageBox.Show("Failed to get init setting.", "Error", MessageBoxButtons.OK);
                txtLog.AppendText("***** Abnormal terminated. *****\r\n");
                return;
            }
            foreach (string strGet in LstrRet)
            {
                txtLog.AppendText(strGet + "\r\n");
                DDIC_Reg_write(strGet.Replace('-', ','));
            }
            txtLog.AppendText("***** Done *****\r\n");

        }
        public bool bStopFlag;      // a flag about process control
        public int nGIR_Oft1_Final;     // the final nGIR_Oft1 value
        string[] GIRoff = { "FE,80", "BD,00", "BE,00", "FE,62", " 31,00 " };
        int tryTimes = 0;
        private bool TuneGIR_Offset1()
        {
            string folder = System.Windows.Forms.Application.StartupPath;
            string strFileName = folder + "\\PartialWhite.bmp";
            double dLuxCurr, dLuxDiff;
            double dLux = 0.0;
            double dx = 0.0;
            double dy = 0.0;
            bool bSkipPageAddr; // index to skip page address query for speeding up the processing performance.
            LstrRet.Clear();
            btnPrevPic(1, 3, Convert.ToDouble(circlePer.Text));  //half
                                                                 //  PF_LoadBMP(strFileName);    // Load PartialWhite.bmp            
            bStopFlag = false;  // set the control flag as false to run
            for (nGIR_Oft1_Final = 0; nGIR_Oft1_Final < 256; nGIR_Oft1_Final++)
            {
                if (bStopFlag)
                {
                    return false;
                }
                bSkipPageAddr = false;  // no skip page address query
                LstrRet.Clear();
                if (!myRAD_IRC.GetCmd_TuneGIR_Offset1(ic_id, nGIR_Oft1_Final, bSkipPageAddr, ref LstrRet))
                {
                    MessageBox.Show("Failed to get GIR Offset1 command.", "Error", MessageBoxButtons.OK);
                    return false;
                }
                txtLog.AppendText("-----------\r\n");
                // list the commands returned                
                foreach (string strGet in LstrRet)
                {
                    // UI_ShowLog(strGet + "\r\n");
                    txtLog.AppendText(strGet + "\r\n");
                    DDIC_Reg_write(strGet.Replace('-', ','));
                }

                Thread.Sleep(500);
                btnPrevPic(1, 3, Convert.ToDouble(circlePer.Text));  //half
                Thread.Sleep(1500);
                frmHelp.Msr_CASDK();
                // get meas.
                //if (!PF_ColorMeterGetMeas(ref dx, ref dy, ref dLux))
                //    return false;
                //UI_ShowLog("[" + nGIR_Oft1_Final.ToString() + "]:\t" + dLux.ToString() + "\r\n\r\n");
                dLuxCurr = frmHelp.CASDK_LUM;
                double diff = stGIR_TuneParam.dTargetLux - dLuxCurr;
                dLuxDiff = Math.Abs(stGIR_TuneParam.dTargetLux - dLuxCurr);
                if ((dLuxDiff * 100) / stGIR_TuneParam.dTargetLux > stGIR_TuneParam.dCritRatio && diff >= 5)
                {
                    tryTimes++;
                    nGIR_Oft1_Final = nGIR_Oft1_Final - 5;

                }

                txtLog.AppendText("nGIR_Oft1_Final=" + nGIR_Oft1_Final.ToString());
                // meet the criterion, break
                if (((dLuxDiff * 100) / stGIR_TuneParam.dTargetLux) < stGIR_TuneParam.dCritRatio || tryTimes == 5)
                {
                    tryTimes = 0;
                    break;
                }
            }
            if (nGIR_Oft1_Final == 256)
            {
                MessageBox.Show("No matching candidates is found.", "Error", MessageBoxButtons.OK);
                return false;
            }
            btnPrevPic(0, 0, Convert.ToDouble(circlePer.Text));  //half
            Thread.Sleep(3000);
            frmHelp.Msr_CASDK();
            stRGBW_255.stCOOR_xyL_R.dx = frmHelp.CASDK_x;
            stRGBW_255.stCOOR_xyL_R.dy = frmHelp.CASDK_y;
            stRGBW_255.stCOOR_xyL_R.dL = frmHelp.CASDK_LUM;

            btnPrevPic(0, 1, Convert.ToDouble(circlePer.Text));  //half
            Thread.Sleep(3000);
            frmHelp.Msr_CASDK();
            stRGBW_255.stCOOR_xyL_G.dx = frmHelp.CASDK_x;
            stRGBW_255.stCOOR_xyL_G.dy = frmHelp.CASDK_y;
            stRGBW_255.stCOOR_xyL_G.dL = frmHelp.CASDK_LUM;
            btnPrevPic(0, 2, Convert.ToDouble(circlePer.Text));  //half
            Thread.Sleep(3000);
            frmHelp.Msr_CASDK();
            stRGBW_255.stCOOR_xyL_B.dx = frmHelp.CASDK_x;
            stRGBW_255.stCOOR_xyL_B.dy = frmHelp.CASDK_y;
            stRGBW_255.stCOOR_xyL_B.dL = frmHelp.CASDK_LUM;
            btnPrevPic(0, 3, Convert.ToDouble(circlePer.Text));  //half
            Thread.Sleep(3000);
            frmHelp.Msr_CASDK();
            stRGBW_255.stCOOR_xyL_W.dx = frmHelp.CASDK_x;
            stRGBW_255.stCOOR_xyL_W.dy = frmHelp.CASDK_y;
            stRGBW_255.stCOOR_xyL_W.dL = frmHelp.CASDK_LUM;
            // get coordate of G255
            txtLog.AppendText("R:" + stRGBW_255.stCOOR_xyL_R.dL.ToString("N4") + "\r\n");
            txtLog.AppendText("G:" + stRGBW_255.stCOOR_xyL_G.dL.ToString("N4") + "\r\n");
            txtLog.AppendText("B:" + stRGBW_255.stCOOR_xyL_B.dL.ToString("N4") + "\r\n");
            txtLog.AppendText("W:" + stRGBW_255.stCOOR_xyL_W.dL.ToString("N4") + "\r\n");
            // Meas and Get RGBW 255 Coodrate            
            //PF_GetRGBW_Coordate(ref stRGBW_255);
            //UI_ShowLog("\r\n");
            //UI_ShowLog("***** Done *****\r\n");
            return true;
        }
        private void BTN_TuneGIR_Offset1_Click(object sender, EventArgs e)
        {
            //Thread Thread_TuneGIR_Offset1;

            //object value = null;
            //Thread_TuneGIR_Offset1 = new Thread(() => { value = TuneGIR_Offset1(); });
            //Thread_TuneGIR_Offset1.IsBackground = true;
            //Thread_TuneGIR_Offset1.Start();
            TuneGIR_Offset1();
        }
        RAD_GIR.Raydium.GMA_SET stGmaSetFinal;      // the final RGB gamma code
        public RAD_GIR.Raydium.COOR_RGBW stRGBW_255;   // RGBW coordate on L255 
        public bool PF_TuneColor(int nColor, double dTargetLux, ST_REG_STRING stRegInput, out int nGmaSet)
        {
            string strCmd;
            int nGmaSetVal, nGmaSetHalf;
            int nGmaCodeMax;
            double dLux, dx, dy, dDiff;
            string strPageAddr;
            dx = 0;
            dy = 0;
            dLux = 0;
            nGmaSet = 0;
            // to get the max. gamma code setting.
            nGmaCodeMax = 0;
            if (!myRAD_IRC.GetGmaCodeMax(ic_id, ref nGmaCodeMax))
            {
                MessageBox.Show("Failed to get Gamma Code Max.", "Error", MessageBoxButtons.OK);
                return false;
            }

            switch (nColor)
            {
                case (int)COLOR_INDEX.COLOR_R:
                    btnPrevPic(0, 0, Convert.ToDouble(circlePer.Text));  //half
                    Thread.Sleep(1000);

                    break;
                case (int)COLOR_INDEX.COLOR_G:
                    btnPrevPic(0, 1, Convert.ToDouble(circlePer.Text));  //half
                    break;
                case (int)COLOR_INDEX.COLOR_B:
                    btnPrevPic(0, 2, Convert.ToDouble(circlePer.Text));  //half
                    break;
                default:
                    MessageBox.Show("Process Color Error.", "Error", MessageBoxButtons.OK);
                    return false;
            }
            // convert hex string to int
            strCmd = stRegInput.strDataH + stRegInput.strDataL;
            nGmaSetVal = Int32.Parse(strCmd, System.Globalization.NumberStyles.HexNumber);
            bStopFlag = false;  // set the control flag as false to run
            while (true)
            {
                if (bStopFlag)
                {
                    return false;
                }
                if (!myRAD_IRC.GetPageAddr(ic_id, RAD_GIR.Raydium.PAGE_ADDR.PA_GMA, out strPageAddr))
                {

                    MessageBox.Show("Get gamma page address failed.", "Error", MessageBoxButtons.OK);
                    return false;
                }
                DDIC_Reg_write(strPageAddr.Replace('-', ','));
                // high byte
                nGmaSetHalf = nGmaSetVal / 256;
                strCmd = String.Format("{0:X2}", nGmaSetHalf);
                strCmd = stRegInput.strRegH + "," + strCmd;
                DDIC_Reg_write(strCmd);
                // low byte
                nGmaSetHalf = nGmaSetVal & 0xFF;
                strCmd = String.Format("{0:X2}", nGmaSetHalf);
                strCmd = stRegInput.strRegL + "," + strCmd;
                DDIC_Reg_write(strCmd);
                // get meas.
                Thread.Sleep(300);
                frmHelp.Msr_CASDK();
                dLux = frmHelp.CASDK_LUM;
                strCmd = String.Format("{0:X4}", nGmaSetVal);
                txtLog.AppendText("" + "Lux [" + strCmd + "]: " + dLux.ToString("N4") + "\r\n");

                dDiff = Math.Abs(dTargetLux - dLux);

                if (((dDiff * 100) / dTargetLux) < stGIR_TuneParam.dCritRatio)
                {
                    nGmaSet = nGmaSetVal;
                    break;
                }

                // not matching the target lux, add 1 to gamma set value
                if (dTargetLux > dLux)
                    nGmaSetVal++;
                else
                    nGmaSetVal--;

                if ((nGmaSetVal < 0) || (nGmaSetVal >= nGmaCodeMax))
                {
                    strCmd = "Gamma Code Setting is under 0.";
                    MessageBox.Show(strCmd, "Error", MessageBoxButtons.OK);
                    return false;
                }

                if (nGmaSetVal >= nGmaCodeMax)
                {
                    strCmd = "Gamma Code Setting is over the limitation. [" + nGmaSetVal.ToString() + "]";
                    MessageBox.Show(strCmd, "Error", MessageBoxButtons.OK);
                    return false;
                }
            }

            DDIC_Reg_write(strPageAddr.Replace('-', ',')); ;

            // high byte
            //nGmaSetHalf = nGmaOrig / 256;
            //strCmd = String.Format("{0:X2}", nGmaSetHalf);
            strCmd = stRegInput.strRegH + "," + stRegInput.strDataH;
            DDIC_Reg_write(strCmd);
            // low byte
            //nGmaSetHalf = nGmaOrig & 0xFF;
            //strCmd = String.Format("{0:X2}", nGmaSetHalf);
            strCmd = stRegInput.strRegL + "," + stRegInput.strDataL;
            DDIC_Reg_write(strCmd);

            return true;
        }
        private bool PDD()
        {
            RAD_GIR.Raydium.GMA_SET stGmaSetOrig, stGmaSetGolden;
            RAD_GIR.Raydium.RGB_LUX stTargetRgbLux;
            //ST_REG_STRING stRegStrR, stRegStrG, stRegStrB;
            //string strVal;

            /*
            stTargetRgbLux.dLuxR = 0;
            stTargetRgbLux.dLuxG = 0;
            stTargetRgbLux.dLuxB = 0;
            */
            // Get the RGB Target Lux

            CRAD_GIRW.GetRGB_TargetLux(stRGBW_255, stGIR_TuneParam.dTargetLux, out stTargetRgbLux);

            txtLog.AppendText("Target Lux: \r\n");
            txtLog.AppendText(stTargetRgbLux.dLuxR.ToString("N4") + "\r\n");
            txtLog.AppendText(stTargetRgbLux.dLuxG.ToString("N4") + "\r\n");
            txtLog.AppendText(stTargetRgbLux.dLuxB.ToString("N4") + "\r\n");
            txtLog.AppendText("\r\n");
            //
            //
            //Get the disable command of GIR Offset1 Control
            //
            //
            LstrRet.Clear();
            myRAD_IRC.GetCmdCtrlGIR_Offset1(ic_id, false, ref LstrRet);
            // list the commands returned
            //UI_ShowLog("*** Commands to control GIR Offset1. ***\r\n");
            foreach (string strGet in LstrRet)
            {
                // UI_ShowLog(strGet + "\r\n");
                DDIC_Reg_write(strGet.Replace('-', ','));
            }
            //UI_ShowLog("\r\n");
            ST_REG_STRING stRegStrR, stRegStrG, stRegStrB;
            // to get the RGB gamma code for the golden RGB 
            stGmaSetGolden.nR = 0;
            stGmaSetGolden.nG = 0;
            stGmaSetGolden.nB = 0;
            // Gamma Code setting of COLOR R-255
            myRAD_IRC.GetGmaRegAddr(ic_id, "R", out stRegStrR.strRegH, out stRegStrR.strRegL);
            stRegStrR.strDataH = TB_R255H.Text;
            stRegStrR.strDataL = TB_R255L.Text;
            // tuning color R to meet the golden lux of color R
            //PF_GetGoldenGmaCodeW255(stTargetRgbLux, out stGmaSetGolden);   // get the orinal W255 gamma code for calculation
            if (!PF_TuneColor((int)COLOR_INDEX.COLOR_R, stTargetRgbLux.dLuxR, stRegStrR, out stGmaSetGolden.nR))
                return false;
            //Gamma Code setting of COLOR G-255
            myRAD_IRC.GetGmaRegAddr(ic_id, "G", out stRegStrG.strRegH, out stRegStrG.strRegL);
            stRegStrG.strDataH = TB_G255H.Text;
            stRegStrG.strDataL = TB_G255L.Text;

            // tuning color G to meet the golden lux of color G
            if (!PF_TuneColor((int)COLOR_INDEX.COLOR_G, stTargetRgbLux.dLuxG, stRegStrG, out stGmaSetGolden.nG))
                return false;

            // Gamma Code setting of COLOR B-255
            myRAD_IRC.GetGmaRegAddr(ic_id, "B", out stRegStrB.strRegH, out stRegStrB.strRegL);
            stRegStrB.strDataH = TB_B255H.Text;
            stRegStrB.strDataL = TB_B255L.Text;
            // tuning color B to meet the golden lux of color B
            if (!PF_TuneColor((int)COLOR_INDEX.COLOR_B, stTargetRgbLux.dLuxB, stRegStrB, out stGmaSetGolden.nB))
                return false;



            string strVal;
            //       PF_GetOrigGmaCodeW255(out stGmaSetOrig);   // get the orinal W255 gamma code for calculation
            strVal = TB_R255H.Text + TB_R255L.Text;
            stGmaSetOrig.nR = Int32.Parse(strVal, System.Globalization.NumberStyles.HexNumber);

            strVal = TB_G255H.Text + TB_G255L.Text;
            stGmaSetOrig.nG = Int32.Parse(strVal, System.Globalization.NumberStyles.HexNumber);

            strVal = TB_B255H.Text + TB_B255L.Text;
            stGmaSetOrig.nB = Int32.Parse(strVal, System.Globalization.NumberStyles.HexNumber);
            //stGmaSetOrig = 0;
            //stGmaSetGolden = 0;
            //// to Get the target RGB Setting
            myRAD_IRC.GetTargetRGB(stGmaSetOrig, stGmaSetGolden, out stGmaSetFinal);

            /*
             * Input Original RGB gamma code settings
             */
            //UI_ShowLog("*** The original RGB gamma code settings *** \r\n");
            //UI_ShowLog("R: " + stGmaSetOrig.nR.ToString() + "(0x" + stGmaSetOrig.nR.ToString("X4") + ")\r\n");
            //UI_ShowLog("G: " + stGmaSetOrig.nG.ToString() + "(0x" + stGmaSetOrig.nG.ToString("X4") + ")\r\n");
            //UI_ShowLog("B: " + stGmaSetOrig.nB.ToString() + "(0x" + stGmaSetOrig.nB.ToString("X4") + ")\r\n");

            ///*
            // * Input Golden RGB Lux
            // */
            //UI_ShowLog("*** The Golden RGB gamma code settings *** \r\n");
            //UI_ShowLog("R: " + stGmaSetGolden.nR.ToString() + "(0x" + stGmaSetGolden.nR.ToString("X4") + ")\r\n");
            //UI_ShowLog("G: " + stGmaSetGolden.nG.ToString() + "(0x" + stGmaSetGolden.nG.ToString("X4") + ")\r\n");
            //UI_ShowLog("B: " + stGmaSetGolden.nB.ToString() + "(0x" + stGmaSetGolden.nB.ToString("X4") + ")\r\n");

            //UI_ShowLog("Final R:" + stGmaSetFinal.nR.ToString() + "  (" + String.Format("{0:X2}", stGmaSetFinal.nR) + "h)" + "\r\n");
            //UI_ShowLog("Final G:" + stGmaSetFinal.nG.ToString() + "  (" + String.Format("{0:X2}", stGmaSetFinal.nG) + "h)" + "\r\n");
            //UI_ShowLog("Final B:" + stGmaSetFinal.nB.ToString() + "  (" + String.Format("{0:X2}", stGmaSetFinal.nB) + "h)" + "\r\n");

            //UI_ShowLog("\r\n");
            //UI_ShowLog("***** Done *****\r\n");

            return true;
        }

        private void BTN_PDD_Click(object sender, EventArgs e)
        {
            //Thread Thread_PDD;
            //object value = null;

            //Thread_PDD = new Thread(() => { value = PDD(); });
            //Thread_PDD.IsBackground = true;
            //Thread_PDD.Start();
            PDD();
        }
        private bool TuneGIR_Offset2()
        {
            double dLuxCurr, dLuxDiff;
            int nGIR_Offset2;
            double dLuxRGB_Sum;
            bool bGIR_Oft2Ctrl;         // the GIR_Offset2 control
            int[] nRatio = new int[3] { 0x40, 0x40, 0x80 };
            string strCmd;
            List<string> strListCmd = new List<string>();


            bStopFlag = false;  // set the control flag as false to run

            nRatio[0] = stGmaSetFinal.nR;
            nRatio[1] = stGmaSetFinal.nG;
            nRatio[2] = stGmaSetFinal.nB;

            LstrRet.Clear();
            bGIR_Oft2Ctrl = false;
            if (!myRAD_IRC.GetCmdFullGIR_Oft2(ic_id, sp, stGIR_TuneParam.nPanelWidth, stGIR_TuneParam.nPanelHeight, bGIR_Oft2Ctrl, nRatio, ref LstrRet))
            {
                MessageBox.Show("Error to get full GIR_Offset2 Commands.", "Error", MessageBoxButtons.OK);
                return false;
            }
            // PF_ExecuteCmd(LstrRet); // execute command for platform dependent

            // List returned commands            
            //  UI_ShowLog("Full Commands to GIR offset2 Tuning with GIR offset2 disabled. \r\n");
            foreach (string strGet in LstrRet)
            {
                txtLog.AppendText(strGet + "\r\n");
                DDIC_Reg_write(strGet.Replace('-', ','));
                //    UI_ShowLog(strGet + "\r\n");
            }
            // UI_ShowLog("\r\n");
            btnPrevPic(0, 0, Convert.ToDouble(circlePer.Text));  //half
            Thread.Sleep(1000);
            frmHelp.Msr_CASDK();
            stRGBW_255.stCOOR_xyL_R.dx = frmHelp.CASDK_x;
            stRGBW_255.stCOOR_xyL_R.dy = frmHelp.CASDK_y;
            stRGBW_255.stCOOR_xyL_R.dL = frmHelp.CASDK_LUM;
            btnPrevPic(0, 1, Convert.ToDouble(circlePer.Text));  //half
            Thread.Sleep(1000);
            frmHelp.Msr_CASDK();
            stRGBW_255.stCOOR_xyL_G.dx = frmHelp.CASDK_x;
            stRGBW_255.stCOOR_xyL_G.dy = frmHelp.CASDK_y;
            stRGBW_255.stCOOR_xyL_G.dL = frmHelp.CASDK_LUM;
            btnPrevPic(0, 2, Convert.ToDouble(circlePer.Text));  //half
            Thread.Sleep(1000);
            frmHelp.Msr_CASDK();
            stRGBW_255.stCOOR_xyL_B.dx = frmHelp.CASDK_x;
            stRGBW_255.stCOOR_xyL_B.dy = frmHelp.CASDK_y;
            stRGBW_255.stCOOR_xyL_B.dL = frmHelp.CASDK_LUM;
            btnPrevPic(0, 3, Convert.ToDouble(circlePer.Text));  //half
            Thread.Sleep(1000);
            frmHelp.Msr_CASDK();
            stRGBW_255.stCOOR_xyL_W.dx = frmHelp.CASDK_x;
            stRGBW_255.stCOOR_xyL_W.dy = frmHelp.CASDK_y;
            stRGBW_255.stCOOR_xyL_W.dL = frmHelp.CASDK_LUM;
            //  PF_GetRGBW_Coordate(ref stRGBW_255);
            dLuxRGB_Sum = stRGBW_255.stCOOR_xyL_R.dL + stRGBW_255.stCOOR_xyL_G.dL + stRGBW_255.stCOOR_xyL_B.dL;

            dLuxCurr = dLuxRGB_Sum;
            dLuxDiff = Math.Abs(stGIR_TuneParam.dTargetLux - dLuxCurr);
            LstrRet.Clear();
            // meet the criterion, break
            if (((dLuxDiff * 100) / stGIR_TuneParam.dTargetLux) < stGIR_TuneParam.dRGBW_CritRatio)
            {

                LstrRet.Clear();
                if (!myRAD_IRC.GetCmdFullGIR_Oft2(ic_id, sp, stGIR_TuneParam.nPanelWidth, stGIR_TuneParam.nPanelHeight, false, nRatio, ref LstrRet))
                {
                    MessageBox.Show("Error to get GIR_Offset2 Commands.", "Error", MessageBoxButtons.OK);
                    return false;
                }

                if (!myRAD_IRC.GetCmd_TuneGIR_Offset1(ic_id, nGIR_Oft1_Final, false, ref LstrRet))
                {
                    MessageBox.Show("Error to get GIR_Offset1 Commands.", "Error", MessageBoxButtons.OK);
                    return false;
                }

                if (!myRAD_IRC.GetCmd_TuneGIR_Offset2(ic_id, 0, ref LstrRet))
                {
                    MessageBox.Show("Error to get GIR_Offset2 Commands.", "Error", MessageBoxButtons.OK);
                    return false;
                }

                foreach (string strGet in LstrRet)
                {
                    txtLog.AppendText(strGet + "\r\n");
                }
                return true;
            }

            for (nGIR_Offset2 = 1; nGIR_Offset2 < 256; nGIR_Offset2++)
            {

                if (bStopFlag)
                {
                    return false;
                }
                LstrRet.Clear();
                if (!myRAD_IRC.GetCmd_TuneGIR_Offset2(ic_id, nGIR_Offset2, ref LstrRet))
                {   // get GIR Offset2 commands
                    MessageBox.Show("Error to get GIR_Offset2 Commands.", "Error", MessageBoxButtons.OK);
                    return false;
                }
                txtLog.AppendText("===========\r\n");
                // PF_ExecuteCmd(LstrRet);     // Convert commands to GDP format and execute
                foreach (string strGet in LstrRet)
                {
                    txtLog.AppendText(strGet + "\r\n");
                    DDIC_Reg_write(strGet.Replace('-', ','));
                    // UI_ShowLog(strGet + "\r\n");
                }
                btnPrevPic(0, 0, Convert.ToDouble(circlePer.Text));  //half
                Thread.Sleep(3000);
                frmHelp.Msr_CASDK();
                stRGBW_255.stCOOR_xyL_R.dx = frmHelp.CASDK_x;
                stRGBW_255.stCOOR_xyL_R.dy = frmHelp.CASDK_y;
                stRGBW_255.stCOOR_xyL_R.dL = frmHelp.CASDK_LUM;

                btnPrevPic(0, 1, Convert.ToDouble(circlePer.Text));  //half
                Thread.Sleep(3000);
                frmHelp.Msr_CASDK();
                stRGBW_255.stCOOR_xyL_G.dx = frmHelp.CASDK_x;
                stRGBW_255.stCOOR_xyL_G.dy = frmHelp.CASDK_y;
                stRGBW_255.stCOOR_xyL_G.dL = frmHelp.CASDK_LUM;
                btnPrevPic(0, 2, Convert.ToDouble(circlePer.Text));  //half
                Thread.Sleep(3000);
                frmHelp.Msr_CASDK();
                stRGBW_255.stCOOR_xyL_B.dx = frmHelp.CASDK_x;
                stRGBW_255.stCOOR_xyL_B.dy = frmHelp.CASDK_y;
                stRGBW_255.stCOOR_xyL_B.dL = frmHelp.CASDK_LUM;
                btnPrevPic(0, 3, Convert.ToDouble(circlePer.Text));  //half
                Thread.Sleep(3000);
                frmHelp.Msr_CASDK();
                stRGBW_255.stCOOR_xyL_W.dx = frmHelp.CASDK_x;
                stRGBW_255.stCOOR_xyL_W.dy = frmHelp.CASDK_y;
                stRGBW_255.stCOOR_xyL_W.dL = frmHelp.CASDK_LUM;
                //   PF_GetRGBW_Coordate(ref stRGBW_255);   // get lux of RGBW255
                dLuxRGB_Sum = stRGBW_255.stCOOR_xyL_R.dL + stRGBW_255.stCOOR_xyL_G.dL + stRGBW_255.stCOOR_xyL_B.dL;

                dLuxCurr = dLuxRGB_Sum;
                dLuxDiff = Math.Abs(stGIR_TuneParam.dTargetLux - dLuxCurr);

                //  UI_ShowLog("dLuxRGB_Sum:" + dLuxRGB_Sum.ToString("N4") + "\r\n");
                // //  UI_ShowLog("dLuxDiff:" + dLuxDiff.ToString("N4") + "\r\n");
                // UI_ShowLog("\r\n");
                double diff = stGIR_TuneParam.dTargetLux - dLuxCurr;

                if ((dLuxDiff * 100) / stGIR_TuneParam.dTargetLux > stGIR_TuneParam.dCritRatio && diff >= 5)
                {
                    tryTimes++;
                    nGIR_Offset2 = nGIR_Offset2 - 5;
                }
                txtLog.AppendText("nGIR_Offset2=" + nGIR_Offset2.ToString());
                // meet the criterion, break
                if (((dLuxDiff * 100) / stGIR_TuneParam.dTargetLux) < stGIR_TuneParam.dRGBW_CritRatio || tryTimes == 5)
                {
                    tryTimes = 0;
                    break;
                }

            }
            if (nGIR_Offset2 == 256)
            {
                MessageBox.Show("No matching candidates (Offset2) is found.", "Error", MessageBoxButtons.OK);
                return false;
            }

            // UI_ShowLog("***** Final Settings are: *****\r\n");

            LstrRet.Clear();
            bGIR_Oft2Ctrl = true;   // enable GIR Offset2 control
            if (!myRAD_IRC.GetCmdFullGIR_Oft2(ic_id, sp, stGIR_TuneParam.nPanelWidth, stGIR_TuneParam.nPanelHeight, bGIR_Oft2Ctrl, nRatio, ref LstrRet))
            {
                MessageBox.Show("Error to get full GIR_Offset2 Commands.", "Error", MessageBoxButtons.OK);
                return false;
            }

            txtLog.AppendText("GetCmdFullGIR_Oft2 ok \r\n");
            if (!myRAD_IRC.GetCmd_TuneGIR_Offset1(ic_id, nGIR_Oft1_Final, false, ref LstrRet))
            {
                MessageBox.Show("Error to get GIR_Offset1 Commands.", "Error", MessageBoxButtons.OK);
                return false;
            }
            txtLog.AppendText("GetCmd_TuneGIR_Offset1 ok \r\n");
            if (!myRAD_IRC.GetCmd_TuneGIR_Offset2(ic_id, nGIR_Offset2, ref LstrRet))
            {
                MessageBox.Show("Error to get GIR_Offset2 Commands.", "Error", MessageBoxButtons.OK);
                return false;
            }
            txtLog.AppendText("GetCmd_TuneGIR_Offset2 ok \r\n");
            /******************************************************
             *
             *  Output the final command result to specific files.
             *
             ******************************************************/
            using (StreamWriter file = new StreamWriter(Application.StartupPath + "\\GIR_FinalSettings.txt"))
            {
                StringBuilder sb = new StringBuilder();

                sb.Append("IC WRITE\r\n");
                foreach (string strGet in LstrRet)
                {
                    //   strCmd = GDP_Ctrl.SplitCmdAndCombine(strGet);
                    //  UI_ShowLog(strCmd + "\r\n");

                    sb.Append(strGet + "\r\n");
                }
                file.Write(sb.ToString());
            }
            // UI_ShowLog("\r\n*****************\r\n\r\n");

            foreach (string Cmd in LstrRet)
                //  UI_ShowLog(Cmd + "\r\n");
                txtLog.AppendText(Cmd + "\r\n");
            //UI_ShowLog("***** Done *****\r\n");
            MessageBox.Show("Done", "Information", MessageBoxButtons.OK);

            return true;
        }
        private void BTN_TuneGIR_Offset2_Click(object sender, EventArgs e)
        {
            //Thread Thread_TuneGIR_Offset2;
            //object value = null;
            //Thread_TuneGIR_Offset2 = new Thread(() => { value = TuneGIR_Offset2(); });
            //Thread_TuneGIR_Offset2.IsBackground = true;
            //Thread_TuneGIR_Offset2.Start();
            TuneGIR_Offset2();
        }

        private void BTN_Stop_Click(object sender, EventArgs e)
        {
            bStopFlag = true;
        }
        private void OneKeyRunAll()
        {
            GetTuneParam();
            //object value = null;
            //Thread_RunInit = new Thread(() => { value = RunInit(); });
            //Thread_RunInit.IsBackground = true;
            //Thread_RunInit.Start();
            RunInit();
            Thread.Sleep(1000);
            BTN_GetSetting_Click(null, null);
            if (TuneGIR_Offset1())
            {
                Thread.Sleep(1000);
                if (PDD())
                {
                    Thread.Sleep(1000);
                    TuneGIR_Offset2();
                }

            }
        }
        private void BTN_OneKey_Click(object sender, EventArgs e)
        {
            //Thread Thread_OneKeyRun;

            //// get the GIR tuning parameters
            //GetTuneParam();

            //Thread_OneKeyRun = new Thread(new ThreadStart(OneKeyRunAll));
            //Thread_OneKeyRun.IsBackground = true;
            //Thread_OneKeyRun.Start();
            OneKeyRunAll();
        }

        private void T20_Tick(object sender, EventArgs e)
        {
            if (rbt_RM690B0_P13.Checked == true)
            {
                RM690B0_Gamma_P13(null, null);
            }
            else if (rbt_RM690B0_P27.Checked == true)
            {
                RM690B0_Gamma_27P(null, null);
            }
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            btnPrevPic(1, 3, 0.5);
        }
        CCGM CGM; //Step 1. Set IC type;
        ColorData InputData = new ColorData();
        List<CGMData> OutputData;
        List<ColorArray> ColorNormalized = new List<ColorArray>
        {
            //new ColorArray { GrayLevel=0,R=0.000000 ,G=0.000000 ,B=0.000000 ,W=0.000000 },
            //new ColorArray { GrayLevel=3,R=0.000226 ,G=0.000276 ,B=0.000298 ,W=0.000471 },
            //new ColorArray { GrayLevel=7,R=0.000829 ,G=0.001118 ,B=0.001245 ,W=0.001483 },
            //new ColorArray { GrayLevel=11,R=0.001854 ,G=0.002226 ,B=0.002767 ,W=0.003123 },
            //new ColorArray { GrayLevel=15,R=0.003423 ,G=0.003922 ,B=0.005390 ,W=0.005478 },
            //new ColorArray { GrayLevel=19,R=0.005662 ,G=0.006134 ,B=0.008473 ,W=0.008721 },
            //new ColorArray { GrayLevel=23,R=0.008420 ,G=0.008994 ,B=0.012405 ,W=0.012538 },
            //new ColorArray { GrayLevel=27,R=0.011443 ,G=0.012341 ,B=0.016522 ,W=0.016882 },
            //new ColorArray { GrayLevel=31,R=0.015220 ,G=0.016260 ,B=0.021857 ,W=0.022329 },
            //new ColorArray { GrayLevel=35,R=0.019945 ,G=0.021073 ,B=0.028111 ,W=0.028562 },
            //new ColorArray { GrayLevel=39,R=0.023935 ,G=0.025290 ,B=0.033292 ,W=0.033930 },
            //new ColorArray { GrayLevel=47,R=0.033233 ,G=0.035423 ,B=0.045995 ,W=0.047493 },
            //new ColorArray { GrayLevel=55,R=0.046027 ,G=0.048234 ,B=0.062087 ,W=0.063716 },
            //new ColorArray { GrayLevel=63,R=0.059607 ,G=0.062822 ,B=0.080383 ,W=0.082527 },
            //new ColorArray { GrayLevel=79,R=0.092490 ,G=0.097070 ,B=0.122239 ,W=0.124223 },
            //new ColorArray { GrayLevel=95,R=0.130837 ,G=0.137253 ,B=0.170929 ,W=0.172772 },
            //new ColorArray { GrayLevel=111,R=0.174438 ,G=0.181567 ,B=0.224909 ,W=0.224460 },
            //new ColorArray { GrayLevel=127,R=0.231307 ,G=0.240208 ,B=0.291564 ,W=0.288297 },
            //new ColorArray { GrayLevel=143,R=0.294731 ,G=0.304574 ,B=0.367615 ,W=0.359228 },
            //new ColorArray { GrayLevel=159,R=0.368302 ,G=0.378561 ,B=0.453035 ,W=0.436868 },
            //new ColorArray { GrayLevel=175,R=0.449989 ,G=0.459607 ,B=0.543691 ,W=0.519301 },
            //new ColorArray { GrayLevel=191,R=0.526005 ,G=0.540391 ,B=0.635449 ,W=0.598619 },
            //new ColorArray { GrayLevel=207,R=0.637350 ,G=0.650718 ,B=0.742637 ,W=0.703337 },
            //new ColorArray { GrayLevel=223,R=0.750255 ,G=0.759215 ,B=0.838253 ,W=0.807816 },
            //new ColorArray { GrayLevel=239,R=0.866283 ,G=0.877385 ,B=0.920091 ,W=0.909659 },
            //new ColorArray { GrayLevel=255,R=1.000000 ,G=1.000000 ,B=1.000000 ,W=1.000000 },
            new ColorArray { GrayLevel=0    ,R=0.000000     ,G=0.000000     ,B=0.000000     ,W=0.000000 }  ,
            new ColorArray { GrayLevel=3    ,R=0.001938     ,G=0.001972     ,B=0.002241     ,W=0.002288 }  ,
            new ColorArray { GrayLevel=7    ,R=0.009019     ,G=0.009201     ,B=0.010119     ,W=0.010383 }  ,
            new ColorArray { GrayLevel=11   ,R=0.021679     ,G=0.023002     ,B=0.023964     ,W=0.025107 }  ,
            new ColorArray { GrayLevel=15   ,R=0.041676     ,G=0.043506     ,B=0.045505     ,W=0.047759 }  ,
            new ColorArray { GrayLevel=19   ,R=0.070129     ,G=0.071597     ,B=0.074256     ,W=0.078656 }  ,
            new ColorArray { GrayLevel=23   ,R=0.104858     ,G=0.106079     ,B=0.109148     ,W=0.115782 }  ,
            new ColorArray { GrayLevel=27   ,R=0.148343     ,G=0.150707     ,B=0.155703     ,W=0.162540 }  ,
            new ColorArray { GrayLevel=31   ,R=0.197779     ,G=0.208226     ,B=0.212489     ,W=0.222127 }  ,
            new ColorArray { GrayLevel=35   ,R=0.262580     ,G=0.267243     ,B=0.274402     ,W=0.283154 }  ,
            new ColorArray { GrayLevel=39   ,R=0.338699     ,G=0.343667     ,B=0.349162     ,W=0.362022 }  ,
            new ColorArray { GrayLevel=47   ,R=0.415029     ,G=0.426192     ,B=0.434041     ,W=0.445214 }  ,
            new ColorArray { GrayLevel=55   ,R=0.509122     ,G=0.515262     ,B=0.526053     ,W=0.536334 }  ,
            new ColorArray { GrayLevel=63   ,R=0.565381     ,G=0.568821     ,B=0.573622     ,W=0.585262 }  ,
            new ColorArray { GrayLevel=79   ,R=0.618539     ,G=0.624155     ,B=0.630707     ,W=0.643753 }  ,
            new ColorArray { GrayLevel=95   ,R=0.675694     ,G=0.684985     ,B=0.685554     ,W=0.694665 }  ,
            new ColorArray { GrayLevel=111  ,R=0.707139     ,G=0.713066     ,B=0.717117     ,W=0.725127 }  ,
            new ColorArray { GrayLevel=127  ,R=0.737959     ,G=0.742090     ,B=0.742462     ,W=0.755161 }  ,
            new ColorArray { GrayLevel=143  ,R=0.769436     ,G=0.776079     ,B=0.779434     ,W=0.786611 }  ,
            new ColorArray { GrayLevel=159  ,R=0.804859     ,G=0.807497     ,B=0.809479     ,W=0.817263 }  ,
            new ColorArray { GrayLevel=175  ,R=0.837188     ,G=0.838527     ,B=0.844095     ,W=0.844637 }  ,
            new ColorArray { GrayLevel=191  ,R=0.870148     ,G=0.870095     ,B=0.874168     ,W=0.879242 }  ,
            new ColorArray { GrayLevel=207  ,R=0.904600     ,G=0.905598     ,B=0.901818     ,W=0.910662 }  ,
            new ColorArray { GrayLevel=223  ,R=0.939970     ,G=0.939662     ,B=0.939224     ,W=0.941221 }  ,
            new ColorArray { GrayLevel=239  ,R=0.974752     ,G=0.975876     ,B=0.973310     ,W=0.976225 }  ,
            new ColorArray { GrayLevel=255  ,R=1.000000     ,G=1.000000     ,B=1.000000     ,W=1.000000 }  ,

        };
        ColorCoordinates Original = new ColorCoordinates
        {
            R = new ColorPoint() { x = 0.68, y = 0.315 },
            G = new ColorPoint() { x = 0.25, y = 0.71 },
            B = new ColorPoint() { x = 0.14, y = 0.047 },
            W = new ColorPoint() { x = 0.30, y = 0.31 },
        };

        ColorCoordinates Target = new ColorCoordinates
        {
            R = new ColorPoint() { x = 0.64, y = 0.33 },
            G = new ColorPoint() { x = 0.3, y = 0.6 },
            B = new ColorPoint() { x = 0.15, y = 0.06 },
            W = new ColorPoint() { x = 0.30, y = 0.31 },
        };

        private void BTN_GET_CGNDATA_Click(object sender, EventArgs e)
        {
            CGM_ERROR_CODE Error_Code;

            ////Step 1. Set IC type;
            CGM = new CCGM(IC_TYPE.RM690B0);

            //Step 2. set input data
            Original.R.x = Convert.ToDouble(RX.Text);
            Original.R.y = Convert.ToDouble(RY.Text);

            Original.G.x = Convert.ToDouble(GX.Text);
            Original.G.y = Convert.ToDouble(GY.Text);

            Original.B.x = Convert.ToDouble(BX.Text);
            Original.B.y = Convert.ToDouble(BY.Text);

            Original.W.x = Convert.ToDouble(WX.Text);
            Original.W.y = Convert.ToDouble(WY.Text);

            InputData.GammaTable = ColorNormalized;
            InputData.Orinigal_ColorCoordinates = Original;
            InputData.Target_ColorCoordinates = Target;
            InputData.Additional_Cmd = 1; //For case 1: To optimize low grey gradient image

            try
            {
                //step 3. get CGM data
                Error_Code = CGM.Get_CGM_Data(InputData, out OutputData);
                if (Error_Code != CGM_ERROR_CODE.CGM_OK)
                {
                    MessageBox.Show("errorcode：", Error_Code.ToString());
                    return;
                }


                txtLog.AppendText("The following is CGM data:\r\n");

                for (int i = 0; i < OutputData.Count; i++)
                {
                    txtLog.AppendText(string.Format("{0:X2}", OutputData[i].Address) + "," + string.Format("{0:X2}", OutputData[i].Data) + "\r\n");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("ERROR:" + ex.Message);
            }

        }

        private void RM690B_B22_ValueChanged(object sender, EventArgs e)
        {

        }

        private void Gamma2_Click(object sender, EventArgs e)
        {
            RM690B0_txtRegData.Text = "FE,00";
            RM690B0_RegWR_Click(RM690B0_RegW, null);
            Thread.Sleep(20);
            RM690B0_txtRegData.Text = "51,FF";
            RM690B0_RegWR_Click(RM690B0_RegW, null);
            Thread.Sleep(20);
            RM690B0_txtRegData.Text = "39";
            RM690B0_RegWR_Click(RM690B0_RegW, null);
            Thread.Sleep(20);
        }

        private void Gamma3_Click(object sender, EventArgs e)
        {
            RM690B0_txtRegData.Text = "FE,00";
            RM690B0_RegWR_Click(RM690B0_RegW, null);
            Thread.Sleep(20);
            RM690B0_txtRegData.Text = "66,02";
            RM690B0_RegWR_Click(RM690B0_RegW, null);
            Thread.Sleep(20);
        }

        private void Gamma4_Click(object sender, EventArgs e)
        {
            RM690B0_txtRegData.Text = "FE,00";
            RM690B0_RegWR_Click(RM690B0_RegW, null);
            Thread.Sleep(20);
            RM690B0_txtRegData.Text = "51,59";
            RM690B0_RegWR_Click(RM690B0_RegW, null);
            Thread.Sleep(20);
            RM690B0_txtRegData.Text = "39";
            RM690B0_RegWR_Click(RM690B0_RegW, null);
            Thread.Sleep(20);
            RM690B0_txtRegData.Text = "FE,00";
            RM690B0_RegWR_Click(RM690B0_RegW, null);
            Thread.Sleep(20);
            RM690B0_txtRegData.Text = "38";
            RM690B0_RegWR_Click(RM690B0_RegW, null);
            Thread.Sleep(20);
            RM690B0_txtRegData.Text = "51,59";
            RM690B0_RegWR_Click(RM690B0_RegW, null);
            Thread.Sleep(20);
        }

        private void Gamma5_Click(object sender, EventArgs e)
        {
            RM690B0_txtRegData.Text = "FE,00";
            RM690B0_RegWR_Click(RM690B0_RegW, null);
            Thread.Sleep(20);
            RM690B0_txtRegData.Text = "51,28";
            RM690B0_RegWR_Click(RM690B0_RegW, null);
            Thread.Sleep(20);
            RM690B0_txtRegData.Text = "39";
            RM690B0_RegWR_Click(RM690B0_RegW, null);
            Thread.Sleep(20);
            RM690B0_txtRegData.Text = "FE,00";
            RM690B0_RegWR_Click(RM690B0_RegW, null);
            Thread.Sleep(20);
            RM690B0_txtRegData.Text = "38";
            RM690B0_RegWR_Click(RM690B0_RegW, null);
            Thread.Sleep(20);
            RM690B0_txtRegData.Text = "51,28";
            RM690B0_RegWR_Click(RM690B0_RegW, null);
            Thread.Sleep(20);
        }

        private void Gamma1_Click(object sender, EventArgs e)
        {
            RM690B0_txtRegData.Text = "FE,00";
            RM690B0_RegWR_Click(RM690B0_RegW, null);
            Thread.Sleep(20);
            RM690B0_txtRegData.Text = "38";
            RM690B0_RegWR_Click(RM690B0_RegW, null);
            Thread.Sleep(20);
            RM690B0_txtRegData.Text = "51,FF";
            RM690B0_RegWR_Click(RM690B0_RegW, null);
            Thread.Sleep(20);
        }

        private void BtnCalculateRM690B0_Click(object sender, EventArgs e)
        {
            double L_X, L_Y, L_Z;
            string[] arr = RM690B0_Gamma_SetBox.Lines;
            {
                try
                {
                    Diven_Gamma.Clear();
                    Diven_Offset.Clear();
                    for (int i = 0; i < arr.Length; i++)
                    {
                        string line = arr[i];
                        line = line.Replace(" ", "");
                        if (line.Contains("TUNING_SPEC"))
                        {
                            line = line.Replace("TUNING_SPEC", "");
                            line = line.Replace("(", "");
                            line = line.Replace(")", "");
                            string[] arr0 = line.Split(',');
                            Setting.Gamma_Property Gamma = new Setting.Gamma_Property(Convert.ToInt32(arr0[0]), Convert.ToDouble(arr0[1]), Convert.ToDouble(arr0[2]), Convert.ToDouble(arr0[3]), Convert.ToDouble(arr0[4]));
                            Diven_Gamma.Add(Gamma);
                        }
                        else if (line.Contains("LXY_SPEC"))
                        {
                            line = line.Replace("LXY_SPEC", "");
                            line = line.Replace("(", "");
                            line = line.Replace(")", "");
                            string[] arr1 = line.Split(',');
                            //将Offset对象放入集合
                            Setting.Offset_Property Offset = new Setting.Offset_Property(Convert.ToInt32(arr1[0]), Convert.ToDouble(arr1[1]), Convert.ToDouble(arr1[2]), Convert.ToDouble(arr1[3]));
                            Diven_Offset.Add(Offset);
                        }
                    }
                }
                catch
                {
                    MessageBox.Show("格式输入有误");
                }
            }

            try  //获取调整spec
            {
                txtRM690B0_loff.Text = Diven_Offset[0].LUM_OFF.ToString();
                txtRM690B0_xoff.Text = Diven_Offset[0].X_OFF.ToString();
                txtRM690B0_yoff.Text = Diven_Offset[0].Y_OFF.ToString();

                Total_points = Diven_Gamma[0].Points_num;
                D_lums = new double[Total_points, 3];
                D_lum = new double[Total_points];

                txtRM690B0_gamma.Text = Diven_Gamma[0].Curve.ToString();
                txtRM690B0_lum.Text = Diven_Gamma[0].Lum.ToString();
                txtRM690B0_x.Text = Diven_Gamma[0].X.ToString();
                txtRM690B0_y.Text = Diven_Gamma[0].Y.ToString();

                for (int i = 0; i < Total_points; i++)
                {   //Diven_Offset[p].NO 灰阶绑点                 
                    D_lum[i] = (Math.Pow((Diven_Offset[i].NO / 255.0), Diven_Gamma[0].Curve) * Diven_Gamma[0].Lum); //每绑点目标亮度
                    CaSDKObj.Lvxy_to_XYZ(D_lum[i], Diven_Gamma[0].X, Diven_Gamma[0].Y, out L_X, out L_Y, out L_Z);//X/Z/Z转换
                    D_lums[i, 0] = L_X; //R/B/G分亮度计算
                    D_lums[i, 1] = L_Y;
                    D_lums[i, 2] = L_Z;
                }
            }
            catch
            {
                MessageBox.Show("格式输入有误");
            }
        }
        private void RM690B0_auto_gamma_write(UInt16 addr, UInt16 datar, UInt16 addg, UInt16 datag, UInt16 addb, UInt16 Datab)//一组gamma写入
        {
            Send_buf = new byte[18];
            Setting.TempRecord.cmdLen = 17;

            Send_buf[0] = 0x76;//RM692EX
                               //  if (radioButton_Page50.Checked == true)
            {
                Send_buf[1] = 0x06; //register normal gamma
            }          //{
            //    Send_buf[1] = 0xDD; //register 
            //}
            Send_buf[2] = 13; //length

            Send_buf[3] = Convert.ToByte(addr >> 8);
            Send_buf[4] = Convert.ToByte(datar >> 8);
            Send_buf[5] = Convert.ToByte(addr & 0xff);
            Send_buf[6] = Convert.ToByte(datar & 0xff);
            Send_buf[7] = Convert.ToByte(addg >> 8);
            Send_buf[8] = Convert.ToByte(datag >> 8);
            Send_buf[9] = Convert.ToByte(addg & 0xff);
            Send_buf[10] = Convert.ToByte(datag & 0xff);
            Send_buf[11] = Convert.ToByte(addb >> 8);
            Send_buf[12] = Convert.ToByte(Datab >> 8);
            Send_buf[13] = Convert.ToByte(addb & 0xff);
            Send_buf[14] = Convert.ToByte(Datab & 0xff);
            if (Gamma1.Checked)
            {
                Send_buf[15] = Convert.ToByte(0);
            }
            else if (Gamma2.Checked)
            {
                Send_buf[15] = Convert.ToByte(1);
            }
            else if (Gamma3.Checked)
            {
                Send_buf[15] = Convert.ToByte(2);
            }
            else if (Gamma4.Checked)
            {
                Send_buf[15] = Convert.ToByte(3);
            }
            else if (Gamma5.Checked)
            {
                Send_buf[15] = Convert.ToByte(4);
            }


            CRCData.CalculateCrc16(Send_buf, out Send_buf[16], out Send_buf[17]);
            try
            {
                frmHelp.comPort.Write(Send_buf, 0, 18);
            }
            catch
            {
                MessageBox.Show("串口有误，请检查", "错误");
                return;
            }
        }


        public void RM690B0_Gamma_P13(Object myObject, EventArgs myEventArgs)
        {
            List<NumericUpDown> R_Value = new List<NumericUpDown> { RM690B_R0, RM690B_R1, RM690B_R2, RM690B_R3, RM690B_R4, RM690B_R5, RM690B_R6, RM690B_R7, RM690B_R8, RM690B_R9, RM690B_R10, RM690B_R11, RM690B_R12, RM690B_R13, RM690B_R14, RM690B_R15, RM690B_R16, RM690B_R17, RM690B_R18, RM690B_R19, RM690B_R20, RM690B_R21, RM690B_R22, RM690B_R23, RM690B_R24, RM690B_R25, RM690B_R26 };
            List<NumericUpDown> G_Value = new List<NumericUpDown> { RM690B_G0, RM690B_G1, RM690B_G2, RM690B_G3, RM690B_G4, RM690B_G5, RM690B_G6, RM690B_G7, RM690B_G8, RM690B_G9, RM690B_G10, RM690B_G11, RM690B_G12, RM690B_G13, RM690B_G14, RM690B_G15, RM690B_G16, RM690B_G17, RM690B_G18, RM690B_G19, RM690B_G20, RM690B_G21, RM690B_G22, RM690B_G23, RM690B_G24, RM690B_G25, RM690B_G26 };
            List<NumericUpDown> B_Value = new List<NumericUpDown> { RM690B_B0, RM690B_B1, RM690B_B2, RM690B_B3, RM690B_B4, RM690B_B5, RM690B_B6, RM690B_B7, RM690B_B8, RM690B_B9, RM690B_B10, RM690B_B11, RM690B_B12, RM690B_B13, RM690B_B14, RM690B_B15, RM690B_B16, RM690B_B17, RM690B_B18, RM690B_B19, RM690B_B20, RM690B_B21, RM690B_B22, RM690B_B23, RM690B_B24, RM690B_B25, RM690B_B26 };

            double L_X, L_Y, L_Z, lumr, lumg, lumb;
            frmHelp.Msr_CASDK();

            if (Gamma_adjust_timeout_flag == true)//如果是0绑点
            {
                flag1 = 0;
                flag2 = 0;
                flag3 = 0;
            }
            else
            {
                if ((frmHelp.CASDK_LUM < (D_lum[index] + D_lum[index] * Diven_Offset[index].LUM_OFF / 100)) && (frmHelp.CASDK_LUM > (D_lum[index] - D_lum[index] * Diven_Offset[index].LUM_OFF / 100)))//G
                { flag1 = 0; }
                else
                { flag1 = 1; }
                if ((frmHelp.CASDK_x < (Diven_Gamma[0].X + Diven_Offset[index].X_OFF)) && (frmHelp.CASDK_x > (Diven_Gamma[0].X - Diven_Offset[index].X_OFF)) && flag1 == 0)//R
                { flag3 = 0; }
                else
                { flag3 = 1; }
                if ((frmHelp.CASDK_y < (Diven_Gamma[0].Y + Diven_Offset[index].Y_OFF)) && (frmHelp.CASDK_y > (Diven_Gamma[0].Y - Diven_Offset[index].Y_OFF)) && flag1 == 0 && flag3 == 0)//B
                { flag2 = 0; }
                else
                { flag2 = 1; }
            }

            if (flag1 == 0 && flag2 == 0 && flag3 == 0)
            {
                T20.Enabled = false;
                //reset-----
                Gamma_adjust_timeout_flag = false;
                frmHelp.Gamma_auto_adjust_count = 0;
                frmHelp.Gamma_auto_adjust_count_set = 40;
                //--------
                index++;

                if (index == Diven_Gamma[0].Points_num)
                {
                    frmHelp.textBox1.Text = frmHelp.textBox1.Text + "RM690B0 gamma调试完毕!\r\n";
                    //---------------------------------add-------------------------------------
                    if (Multi_gamma_txt_next_index < Multi_gamma_txt_line_count)
                    {
                        Multi_gamma_txt_now_index = Multi_gamma_txt_next_index;
                        Multi_flexible_gammas(Multi_gamma_txt_now_index, out Multi_gamma_txt_next_index);
                    }
                    //---------------------------------add-------------------------------------
                }
                if (index < Diven_Gamma[0].Points_num)
                {

                    frmHelp.numPatternR.Value = Diven_Offset[index].NO;//固定255灰阶
                    frmHelp.numPatternG.Value = Diven_Offset[index].NO;
                    frmHelp.numPatternB.Value = Diven_Offset[index].NO;
                    Application.DoEvents();
                    frmHelp.OLED_Show_Click(frmHelp.btnPatternW, null);//写入Pattern参数

                    Thread.Sleep(1000); //1秒=1000毫秒，
                    T20.Enabled = true;
                    flag1 = 1;
                    flag2 = 1;
                    flag3 = 1;
                }
            }
            else
            {
                decimal r = 0, g = 0, b = 0;
                frmHelp.Gamma_auto_adjust_count_set = 50;
                CaSDKObj.Lvxy_to_XYZ(frmHelp.CASDK_LUM, frmHelp.CASDK_x, frmHelp.CASDK_y, out L_X, out L_Y, out L_Z);
                lumr = L_X;
                lumg = L_Y;
                lumb = L_Z;

                try
                {
                    switch (index)
                    {
                        case 0:
                        case 1:
                        case 2:
                        case 3:
                        case 4:
                        case 5:
                        case 6:
                        case 7:
                        case 8:
                        case 9:
                        case 10:
                            {
                                frmHelp.Flexible_Gamma_auto_Adujst(flag1, flag3, flag2, lumg, lumr, lumb, D_lums[index, 1], D_lums[index, 0], D_lums[index, 2], R_Value[index + 14].Value, G_Value[index + 14].Value, B_Value[index + 14].Value, Diven_Offset[index].NO, 0x3FF, out r, out g, out b, out Gamma_adjust_timeout_flag);
                                if (Gamma_adjust_timeout_flag == true)
                                {
                                    flag1 = 0; flag3 = 0; flag2 = 0;
                                }
                                if (index > 0)
                                {
                                    if (r > R_Value[14 + index - 1].Value)
                                    {
                                        r = R_Value[14 + index - 1].Value - 10;
                                    }
                                    if (g > G_Value[14 + index - 1].Value)
                                    {
                                        g = G_Value[14 + index - 1].Value - 10;
                                    }
                                    if (b > B_Value[14 + index - 1].Value)
                                    {
                                        b = B_Value[14 + index - 1].Value - 10;
                                    }
                                }
                                if (R_Value[14 + index].Value < R_Value[14 + index + 1].Value)
                                {
                                    R_Value[14 + index + 1].Value = R_Value[14 + index].Value - 20;
                                }
                                if (G_Value[14 + index].Value < G_Value[14 + index + 1].Value)
                                {
                                    G_Value[14 + index + 1].Value = G_Value[14 + index].Value - 20;
                                }
                                if (B_Value[14 + index].Value < B_Value[14 + index + 1].Value)
                                {
                                    B_Value[14 + index + 1].Value = B_Value[14 + index].Value - 20;
                                }
                                RM690B0_auto_gamma_write(gamma_r[11 - index], (ushort)R_Value[14 + index + 1].Value, gamma_g[11 - index],
                                    (ushort)G_Value[14 + index + 1].Value, gamma_b[11 - index], (ushort)B_Value[14 + index + 1].Value);
                            }
                            break;

                        case 11:
                            {
                                Gamma_adjust_timeout_flag = true;
                                r = (int)R_Value[14 - 1 + index].Value / 2;
                                g = (int)G_Value[14 - 1 + index].Value / 2;
                                b = (int)B_Value[14 - 1 + index].Value / 2;

                            }
                            break;
                        case 12:
                            {
                                Gamma_adjust_timeout_flag = true;
                                r = R_Value[14 + index].Value = 0;
                                g = G_Value[14 + index].Value = 0;
                                b = B_Value[14 + index].Value = 0;
                            }
                            break;
                        default:
                            break;
                    }
                    R_Value[14 + index].Value = r;
                    G_Value[14 + index].Value = g;
                    B_Value[14 + index].Value = b;
                    RM690B0_auto_gamma_write(gamma_r[12 - index], (ushort)r, gamma_g[12 - index], (ushort)g, gamma_b[12 - index], (ushort)b);


                }
                catch
                {
                    T20.Enabled = false;
                    MessageBox.Show("调整数值超限");
                }
            }
        }
        public void RM690B0_Gamma_27P(Object myObject, EventArgs myEventArgs)
        {
            List<NumericUpDown> R_Value = new List<NumericUpDown> { RM690B_R0, RM690B_R1, RM690B_R2, RM690B_R3, RM690B_R4, RM690B_R5, RM690B_R6, RM690B_R7, RM690B_R8, RM690B_R9, RM690B_R10, RM690B_R11, RM690B_R12, RM690B_R13, RM690B_R14, RM690B_R15, RM690B_R16, RM690B_R17, RM690B_R18, RM690B_R19, RM690B_R20, RM690B_R21, RM690B_R22, RM690B_R23, RM690B_R24, RM690B_R25, RM690B_R26 };
            List<NumericUpDown> G_Value = new List<NumericUpDown> { RM690B_G0, RM690B_G1, RM690B_G2, RM690B_G3, RM690B_G4, RM690B_G5, RM690B_G6, RM690B_G7, RM690B_G8, RM690B_G9, RM690B_G10, RM690B_G11, RM690B_G12, RM690B_G13, RM690B_G14, RM690B_G15, RM690B_G16, RM690B_G17, RM690B_G18, RM690B_G19, RM690B_G20, RM690B_G21, RM690B_G22, RM690B_G23, RM690B_G24, RM690B_G25, RM690B_G26 };
            List<NumericUpDown> B_Value = new List<NumericUpDown> { RM690B_B0, RM690B_B1, RM690B_B2, RM690B_B3, RM690B_B4, RM690B_B5, RM690B_B6, RM690B_B7, RM690B_B8, RM690B_B9, RM690B_B10, RM690B_B11, RM690B_B12, RM690B_B13, RM690B_B14, RM690B_B15, RM690B_B16, RM690B_B17, RM690B_B18, RM690B_B19, RM690B_B20, RM690B_B21, RM690B_B22, RM690B_B23, RM690B_B24, RM690B_B25, RM690B_B26 };

            double L_X, L_Y, L_Z, lumr, lumg, lumb;
            frmHelp.Msr_CASDK();

            if (Gamma_adjust_timeout_flag == true)//如果是0绑点
            {
                flag1 = 0;
                flag2 = 0;
                flag3 = 0;
            }
            else
            {
                if ((frmHelp.CASDK_LUM < (D_lum[index] + D_lum[index] * Diven_Offset[index].LUM_OFF / 100)) && (frmHelp.CASDK_LUM > (D_lum[index] - D_lum[index] * Diven_Offset[index].LUM_OFF / 100)))//G
                { flag1 = 0; }
                else
                { flag1 = 1; }
                if ((frmHelp.CASDK_x < (Diven_Gamma[0].X + Diven_Offset[index].X_OFF)) && (frmHelp.CASDK_x > (Diven_Gamma[0].X - Diven_Offset[index].X_OFF)) && flag1 == 0)//R
                { flag3 = 0; }
                else
                { flag3 = 1; }
                if ((frmHelp.CASDK_y < (Diven_Gamma[0].Y + Diven_Offset[index].Y_OFF)) && (frmHelp.CASDK_y > (Diven_Gamma[0].Y - Diven_Offset[index].Y_OFF)) && flag1 == 0 && flag3 == 0)//B
                { flag2 = 0; }
                else
                { flag2 = 1; }
            }

            if (flag1 == 0 && flag2 == 0 && flag3 == 0)
            {
                T20.Enabled = false;
                //reset-----
                Gamma_adjust_timeout_flag = false;
                frmHelp.Gamma_auto_adjust_count = 0;
                frmHelp.Gamma_auto_adjust_count_set = 50;
                //--------
                index++;

                if (index == Diven_Gamma[0].Points_num)
                {
                    frmHelp.textBox1.Text = frmHelp.textBox1.Text + "RM690B0 gamma调试完毕!\r\n";
                    //---------------------------------add-------------------------------------
                    if (Multi_gamma_txt_next_index < Multi_gamma_txt_line_count)
                    {
                        Multi_gamma_txt_now_index = Multi_gamma_txt_next_index;
                        Multi_flexible_gammas(Multi_gamma_txt_now_index, out Multi_gamma_txt_next_index);
                    }
                    //---------------------------------add-------------------------------------
                }
                if (index < Diven_Gamma[0].Points_num)
                {

                    frmHelp.numPatternR.Value = Diven_Offset[index].NO;//固定255灰阶
                    frmHelp.numPatternG.Value = Diven_Offset[index].NO;
                    frmHelp.numPatternB.Value = Diven_Offset[index].NO;
                    Application.DoEvents();
                    frmHelp.OLED_Show_Click(frmHelp.btnPatternW, null);//写入Pattern参数

                    Thread.Sleep(50); //1秒=1000毫秒，
                    T20.Enabled = true;
                    flag1 = 1;
                    flag2 = 1;
                    flag3 = 1;
                }
            }
            else
            {
                decimal r = 0, g = 0, b = 0;
                frmHelp.Gamma_auto_adjust_count_set = 50;
                CaSDKObj.Lvxy_to_XYZ(frmHelp.CASDK_LUM, frmHelp.CASDK_x, frmHelp.CASDK_y, out L_X, out L_Y, out L_Z);
                lumr = L_X;
                lumg = L_Y;
                lumb = L_Z;

                try
                {
                    switch (index)
                    {
                        case 0:
                        case 1:
                        case 2:
                        case 3:
                        case 4:
                        case 5:
                        case 6:
                        case 7:
                        case 8:
                        case 9:
                        case 10:
                        case 11:
                        case 12:
                        case 13:
                        case 14:
                        case 15:
                        case 16:
                        case 17:
                        case 18:
                        case 19:
                        case 20:
                        case 21:
                        case 22:
                        case 23:
                        case 24:
                            {
                                frmHelp.Flexible_Gamma_auto_Adujst(flag1, flag3, flag2, lumg, lumr, lumb, D_lums[index, 1], D_lums[index, 0], D_lums[index, 2], R_Value[index].Value, G_Value[index].Value, B_Value[index].Value, Diven_Offset[index].NO, 0x3FF, out r, out g, out b, out Gamma_adjust_timeout_flag);
                                if (Gamma_adjust_timeout_flag == true)
                                {
                                    flag1 = 0; flag3 = 0; flag2 = 0;
                                }
                                if (index > 0)
                                {
                                    if (r > R_Value[index - 1].Value)
                                    {
                                        r = R_Value[index - 1].Value - 10;
                                    }
                                    if (g > G_Value[index - 1].Value)
                                    {
                                        g = G_Value[index - 1].Value - 10;
                                    }
                                    if (b > B_Value[index - 1].Value)
                                    {
                                        b = B_Value[index - 1].Value - 10;
                                    }
                                }

                                R_Value[index].Value = r;
                                G_Value[index].Value = g;
                                B_Value[index].Value = b;

                                if (R_Value[index].Value < R_Value[index + 1].Value)
                                {
                                    R_Value[index + 1].Value = R_Value[index].Value - 10;
                                }
                                if (G_Value[index].Value < G_Value[index + 1].Value)
                                {
                                    G_Value[index + 1].Value = G_Value[index].Value - 10;
                                }
                                if (B_Value[index].Value < B_Value[index + 1].Value)
                                {
                                    B_Value[index + 1].Value = B_Value[index].Value - 10;
                                }
                                RM690B0_auto_gamma_write(gamma_r[25 - index], (ushort)R_Value[index + 1].Value, gamma_g[25 - index],
                                    (ushort)G_Value[index + 1].Value, gamma_b[25 - index], (ushort)B_Value[index + 1].Value);

                            }
                            break;

                        case 25:
                            {
                                Gamma_adjust_timeout_flag = true;
                                r = (int)R_Value[index - 1].Value / 2;
                                g = (int)G_Value[index - 1].Value / 2;
                                b = (int)B_Value[index - 1].Value / 2;

                            }
                            break;
                        case 26:
                            {
                                Gamma_adjust_timeout_flag = true;
                                r = R_Value[index].Value = 0;
                                g = G_Value[index].Value = 0;
                                b = B_Value[index].Value = 0;


                            }
                            break;
                        default:
                            break;
                    }

                    R_Value[index].Value = r;
                    G_Value[index].Value = g;
                    B_Value[index].Value = b;
                    // RM690B0_GAMMA_Click(RM690B0_GammaW_Blue, null);
                    //  RM690B0_GAMMA_Click(RM690B0_GammaW_Green, null);
                    // RM690B0_GAMMA_Click(RM690B0_GammaW_Red, null);
                    RM690B0_auto_gamma_write(gamma_r[26 - index], (ushort)r, gamma_g[26 - index], (ushort)g, gamma_b[26 - index], (ushort)b);
                }
                catch
                {
                    T20.Enabled = false;
                    MessageBox.Show("调整数值超限");

                }
            }
        }



        //---------------------------------add-------------------------------------
        private int Multi_gamma_txt_now_index = 0;
        private int Multi_gamma_txt_next_index;
        private int Multi_gamma_txt_line_count = 0;
        private int Multi_gamma_group_index = 0;
        private void Btn_flexible_gamma_Click(object sender, EventArgs e)
        {
            Multi_gamma_txt_now_index = 0;
            Multi_gamma_txt_line_count = this.RM690B0_Gamma_SetBox.Lines.GetUpperBound(0);
            Multi_flexible_gammas(Multi_gamma_txt_now_index, out Multi_gamma_txt_next_index);
        }
        private void Multi_flexible_gammas(int txt_index, out int list_view_index)
        {
            string strLine = Convert.ToString(RM690B0_Gamma_SetBox.Text);
            string[] arr = strLine.Split(','); //以逗号分割，添加到数组
            string perline = string.Empty;
            string perline0 = string.Empty;
            list_view_index = 0;

            if (RM690B0_Gamma_SetBox.Text == string.Empty)
            {
                MessageBox.Show("内容为空!");
            }
            else  //标记关键事件
            {
                try
                {
                    arr = strLine.Split('\n'); //以逗号分割，添加到数
                    for (int i = txt_index; i < arr.Length;)  //获取的行数
                    {
                        perline = arr[i];
                        perline = perline.Replace(" ", "");
                        perline = perline.Replace(";", "");
                        perline = perline.Replace("(", "");
                        perline = perline.Replace(")", "");
                        perline = perline.Replace("\r", "");

                        if (perline.Contains("REGW"))
                        {
                            perline = perline.Replace("REGW", "");
                            RM690B0_txtRegData.Text = perline;
                            RM690B0_RegWR_Click(RM690B0_RegW, null);
                            Thread.Sleep(200);
                            i = i + 1;
                        }

                        else if (perline.Contains("SAVE"))
                        {
                            string pathsave_file = System.Environment.CurrentDirectory + "\\l_gamma";
                            if (Directory.Exists(pathsave_file) == false)
                            {
                                Directory.CreateDirectory(pathsave_file);
                            }
                            string pathsave = System.Environment.CurrentDirectory + "\\l_gamma" + "\\gamma" + Multi_gamma_group_index.ToString() + ".csv";
                            Multi_SaveGamma(pathsave);
                            Thread.Sleep(50);
                            i = i + 1;
                        }
                        else if (perline.Contains("GAMMA_SET"))
                        {
                            perline = perline.Replace("GAMMA_SET", "");
                            perline = perline.Replace("_", "");
                            Multi_gamma_group_index = Convert.ToInt32(perline);
                            System.Diagnostics.Debug.Print(Multi_gamma_group_index.ToString());             // 华丽的分割线----------------------

                            if (Multi_gamma_group_index == 0)
                            {
                                Gamma1.Checked = true;
                            }
                            else if (Multi_gamma_group_index == 1)
                            {
                                Gamma2.Checked = true;
                            }
                            else if (Multi_gamma_group_index == 2)
                            {
                                Gamma3.Checked = true;
                            }
                            else if (Multi_gamma_group_index == 3)
                            {
                                Gamma4.Checked = true;
                            }
                            else if (Multi_gamma_group_index == 4)
                            {
                                Gamma5.Checked = true;
                            }

                            ArrayList list = new ArrayList();
                            do
                            {
                                i = i + 1;
                                perline = arr[i];
                                list.Add(perline + "\n");
                            } while (perline.Contains("GAMMA_TUNING") == false);
                            string[] gamma_set_lines = (string[])list.ToArray(typeof(string));
                            for (int j = 0; j < gamma_set_lines.Length; j++)                        // 华丽的分割线----------------------
                            {
                                System.Diagnostics.Debug.Print(gamma_set_lines[j]);             // 华丽的分割线----------------------
                            }

                            Text_Processing(gamma_set_lines);
                            try
                            {
                                string pathsave_file = System.Environment.CurrentDirectory + "\\l_gamma";
                                if (Directory.Exists(pathsave_file) == false)
                                {
                                    Directory.CreateDirectory(pathsave_file);
                                }
                                string pathload = System.Environment.CurrentDirectory + "\\l_gamma" + "\\gamma" + Multi_gamma_group_index.ToString() + ".csv";
                                Multi_LoadGamma(pathload);
                                Application.DoEvents();

                                RM690B0_GAMMA_Click(RM690B0_GammaW_Red, null);
                                Thread.Sleep(20);
                                RM690B0_GAMMA_Click(RM690B0_GammaW_Green, null);
                                Thread.Sleep(20);
                                RM690B0_GAMMA_Click(RM690B0_GammaW_Blue, null);
                                Thread.Sleep(20);
                            }
                            catch {; }
                            if (Total_points > 15)
                            {
                                rbt_RM690B0_P27.Checked = true;
                            }
                            btnAutoGammas_RM690B0_Click(null, null); //替换成相应IC的自动gamma启动函数名
                            list_view_index = i;
                            break;
                        }
                        else
                        {
                            i = i + 1;
                        }
                    }
                }
                catch
                {
                    MessageBox.Show("输入格式有误！");
                }
            }
        }
        private void Text_Processing(string[] txt_path)
        {
            double L_X, L_Y, L_Z;
            string[] arr = txt_path;
            {
                try
                {
                    Diven_Gamma.Clear();
                    Diven_Offset.Clear();
                    for (int i = 0; i < arr.Length; i++)
                    {
                        string line = arr[i];
                        line = line.Replace(" ", "");
                        if (line.Contains("TUNING_SPEC"))
                        {
                            line = line.Replace("TUNING_SPEC", "");
                            line = line.Replace("(", "");
                            line = line.Replace(")", "");
                            string[] arr0 = line.Split(',');
                            Setting.Gamma_Property Gamma = new Setting.Gamma_Property(Convert.ToInt32(arr0[0]), Convert.ToDouble(arr0[1]), Convert.ToDouble(arr0[2]), Convert.ToDouble(arr0[3]), Convert.ToDouble(arr0[4]));
                            Diven_Gamma.Add(Gamma);
                        }
                        else if (line.Contains("LXY_SPEC"))
                        {
                            line = line.Replace("LXY_SPEC", "");
                            line = line.Replace("(", "");
                            line = line.Replace(")", "");
                            string[] arr1 = line.Split(',');
                            //将Offset对象放入集合
                            Setting.Offset_Property Offset = new Setting.Offset_Property(Convert.ToInt32(arr1[0]), Convert.ToDouble(arr1[1]), Convert.ToDouble(arr1[2]), Convert.ToDouble(arr1[3]));
                            Diven_Offset.Add(Offset);
                        }
                    }
                }
                catch
                {
                    MessageBox.Show("格式输入有误");
                }
            }
            try  //获取调整spec
            {
                txtRM690B0_loff.Text = Diven_Offset[0].LUM_OFF.ToString();
                txtRM690B0_xoff.Text = Diven_Offset[0].X_OFF.ToString();
                txtRM690B0_yoff.Text = Diven_Offset[0].Y_OFF.ToString();

                Total_points = Diven_Gamma[0].Points_num;
                D_lums = new double[Total_points, 3];
                D_lum = new double[Total_points];

                txtRM690B0_gamma.Text = Diven_Gamma[0].Curve.ToString();
                txtRM690B0_lum.Text = Diven_Gamma[0].Lum.ToString();
                txtRM690B0_x.Text = Diven_Gamma[0].X.ToString();
                txtRM690B0_y.Text = Diven_Gamma[0].Y.ToString();

                for (int i = 0; i < Total_points; i++)
                {   //Diven_Offset[p].NO 灰阶绑点                 
                    D_lum[i] = (Math.Pow((Diven_Offset[i].NO / 255.0), Diven_Gamma[0].Curve) * Diven_Gamma[0].Lum); //每绑点目标亮度
                    CaSDKObj.Lvxy_to_XYZ(D_lum[i], Diven_Gamma[0].X, Diven_Gamma[0].Y, out L_X, out L_Y, out L_Z);//X/Z/Z转换
                    D_lums[i, 0] = L_X; //R/B/G分亮度计算
                    D_lums[i, 1] = L_Y;
                    D_lums[i, 2] = L_Z;
                }
            }
            catch
            {
                MessageBox.Show("格式输入有误");
            }
        }

        //---------------------------------add-------------------------------------
        //Gamma自动保存
        private void Multi_SaveGamma(string path)
        {
            List<NumericUpDown> R_Value = new List<NumericUpDown> { RM690B_R0, RM690B_R1, RM690B_R2, RM690B_R3, RM690B_R4, RM690B_R5, RM690B_R6, RM690B_R7, RM690B_R8, RM690B_R9, RM690B_R10, RM690B_R11, RM690B_R12, RM690B_R13, RM690B_R14, RM690B_R15, RM690B_R16, RM690B_R17, RM690B_R18, RM690B_R19, RM690B_R20, RM690B_R21, RM690B_R22, RM690B_R23, RM690B_R24, RM690B_R25, RM690B_R26 };
            List<NumericUpDown> G_Value = new List<NumericUpDown> { RM690B_G0, RM690B_G1, RM690B_G2, RM690B_G3, RM690B_G4, RM690B_G5, RM690B_G6, RM690B_G7, RM690B_G8, RM690B_G9, RM690B_G10, RM690B_G11, RM690B_G12, RM690B_G13, RM690B_G14, RM690B_G15, RM690B_G16, RM690B_G17, RM690B_G18, RM690B_G19, RM690B_G20, RM690B_G21, RM690B_G22, RM690B_G23, RM690B_G24, RM690B_G25, RM690B_G26 };
            List<NumericUpDown> B_Value = new List<NumericUpDown> { RM690B_B0, RM690B_B1, RM690B_B2, RM690B_B3, RM690B_B4, RM690B_B5, RM690B_B6, RM690B_B7, RM690B_B8, RM690B_B9, RM690B_B10, RM690B_B11, RM690B_B12, RM690B_B13, RM690B_B14, RM690B_B15, RM690B_B16, RM690B_B17, RM690B_B18, RM690B_B19, RM690B_B20, RM690B_B21, RM690B_B22, RM690B_B23, RM690B_B24, RM690B_B25, RM690B_B26 };
            try
            {
                string str = "保存Gamma文件";
                StreamWriter sw = null; //文件流
                sw = new StreamWriter(path, false, Encoding.UTF8);
                for (int i = 0; i < 27; i++)
                {
                    string temp = P27_Grey[i].ToString();
                    str = str + "R" + temp + "," + R_Value[26 - i].Text + "," + "G" + temp + "," + G_Value[26 - i].Text + "," + "B" + temp + "," + B_Value[26 - i].Text + "\r\n";
                }
                sw.WriteLine(str);
                sw.Dispose(); //释放资源
                sw.Close(); //关闭数据流
            }
            catch
            {
                MessageBox.Show("Gamma保存时发生错误，请再试！", "系统提示：");
            }
        } //

        //Gamma自动载入
        private void Multi_LoadGamma(string path)
        {
            string strtmp = "";
            //读取文本信息
            FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
            StreamReader streamReader = new StreamReader(fs, Encoding.GetEncoding("GBK"));
            streamReader.BaseStream.Seek(0, SeekOrigin.Begin);
            string strLine = streamReader.ReadLine();
            //循环读取文本信息
            while (!string.IsNullOrEmpty(strLine))
            {
                strtmp = strtmp + strLine + ",";
                strLine = streamReader.ReadLine(); //循环读取下一行
            }
            fs.Close(); //关闭流
            streamReader.Close();
            string[] arrtmp = strtmp.Split(new Char[] { ',' });
            List<NumericUpDown> R_Value = new List<NumericUpDown> { RM690B_R0, RM690B_R1, RM690B_R2, RM690B_R3, RM690B_R4, RM690B_R5, RM690B_R6, RM690B_R7, RM690B_R8, RM690B_R9, RM690B_R10, RM690B_R11, RM690B_R12, RM690B_R13, RM690B_R14, RM690B_R15, RM690B_R16, RM690B_R17, RM690B_R18, RM690B_R19, RM690B_R20, RM690B_R21, RM690B_R22, RM690B_R23, RM690B_R24, RM690B_R25, RM690B_R26 };
            List<NumericUpDown> G_Value = new List<NumericUpDown> { RM690B_G0, RM690B_G1, RM690B_G2, RM690B_G3, RM690B_G4, RM690B_G5, RM690B_G6, RM690B_G7, RM690B_G8, RM690B_G9, RM690B_G10, RM690B_G11, RM690B_G12, RM690B_G13, RM690B_G14, RM690B_G15, RM690B_G16, RM690B_G17, RM690B_G18, RM690B_G19, RM690B_G20, RM690B_G21, RM690B_G22, RM690B_G23, RM690B_G24, RM690B_G25, RM690B_G26 };
            List<NumericUpDown> B_Value = new List<NumericUpDown> { RM690B_B0, RM690B_B1, RM690B_B2, RM690B_B3, RM690B_B4, RM690B_B5, RM690B_B6, RM690B_B7, RM690B_B8, RM690B_B9, RM690B_B10, RM690B_B11, RM690B_B12, RM690B_B13, RM690B_B14, RM690B_B15, RM690B_B16, RM690B_B17, RM690B_B18, RM690B_B19, RM690B_B20, RM690B_B21, RM690B_B22, RM690B_B23, RM690B_B24, RM690B_B25, RM690B_B26 };
            for (int i = 0; i < 27; i++)
            {
                R_Value[26 - i].Text = arrtmp[6 * i + 1].ToString();
                G_Value[26 - i].Text = arrtmp[6 * i + 3].ToString();
                B_Value[26 - i].Text = arrtmp[6 * i + 5].ToString();
            }
        }



        private void 保存ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (RM690B0_Gamma_SetBox.Text == string.Empty)
            {
                MessageBox.Show("内容为空!");
            }
            else
            {
                //创建保存对话框对象
                SaveFileDialog save = new SaveFileDialog();
                save.Filter = "gamma cfg files (*.txt)|*.txt"; //过滤文件类型
                save.FilterIndex = 1;
                save.RestoreDirectory = true;
                if (save.ShowDialog() == DialogResult.OK)
                {
                    string path = save.FileName;
                    save.DefaultExt = ".txt";
                    StreamWriter sw = new StreamWriter(path);
                    sw.WriteLine(RM690B0_Gamma_SetBox.Text);
                    sw.Close();
                }
            }
        }
        private void 载入ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog of = new OpenFileDialog();
            of.Filter = "精度配置文件(*.txt)|*.txt|所有文件(*.*)|*.*";
            of.Title = "gamma cfg write";

            if (of.ShowDialog() == DialogResult.OK)
            {
                RM690B0_Gamma_SetBox.Clear();
                //读取文本信息
                FileStream fs = new FileStream(of.FileName, FileMode.Open, FileAccess.Read);
                StreamReader streamReader = new StreamReader(fs, Encoding.GetEncoding("GBK"));
                streamReader.BaseStream.Seek(0, SeekOrigin.Begin);
                string str_generate = streamReader.ReadLine();
                //循环读取文本信息
                while (str_generate != null)
                {
                    RM690B0_Gamma_SetBox.AppendText(str_generate + "\r\n");
                    str_generate = streamReader.ReadLine(); //循环读取下一行
                }
                fs.Close(); //关闭流
                streamReader.Close();
            }
        }
        private void btnPrevPic(int shapeType, int RGBWtype, double mult)       //双击 载入 BMP图片shapeType 0=rectangle 1=circle RGBWtype 0=R,1=G,2=B,3=W
        {
            Int32 HACT_True = (int)frmHelp.HACT.Value;
            Int32 HACT_Skip = 0;
            Int32 VACT_True = (int)frmHelp.VACT.Value;
            Int32 m_txlen = 0;
            Int32 j = 0;
            FileStream aFile;
            byte tep;
            Bitmap image1 = new Bitmap(HACT_True, VACT_True, PixelFormat.Format24bppRgb);
            if (shapeType == 1)
            {
                for (int i = 0; i < HACT_True; i++)
                {
                    for (int jt = 0; jt < VACT_True; jt++)
                    {
                        if (((i - HACT_True * 0.5) * (i - HACT_True * 0.5) + (jt - HACT_True * 0.5) * (jt - HACT_True * 0.5)) <= (int)(HACT_True * mult * 0.5) * (int)(HACT_True * mult * 0.5))
                        {
                            image1.SetPixel(i, jt, Color.FromArgb(255, 255, 255));
                        }
                        else
                            image1.SetPixel(i, jt, Color.FromArgb(0, 0, 0));
                    }
                }
            }
            else if (shapeType == 0)
            {
                for (int i = 0; i < HACT_True; i++)
                {
                    for (int jt = 0; jt < VACT_True; jt++)
                    {
                        switch (RGBWtype)
                        {
                            case 0:
                                {
                                    image1.SetPixel(i, jt, Color.FromArgb(255, 0, 0));
                                }
                                break;
                            case 1:
                                {
                                    image1.SetPixel(i, jt, Color.FromArgb(0, 255, 0));
                                }
                                break;
                            case 2:
                                {
                                    image1.SetPixel(i, jt, Color.FromArgb(0, 0, 255));
                                }
                                break;
                            case 3:
                                {
                                    image1.SetPixel(i, jt, Color.FromArgb(255, 255, 255));
                                }
                                break;
                            default:
                                break;
                        }
                    }
                }
            }
            image1.Save("./123456789.bmp", ImageFormat.Bmp);
            //MemoryStream ms = null;
            //string temp = null;
            //{
            //    ms = new MemoryStream();
            //    image1.Save(ms, ImageFormat.Bmp);
            //    byte[] byteImage = new Byte[ms.Length];
            //    byteImage = ms.ToArray();

            //    for (int i = 0; i < 54; i++)
            //    {
            //        temp= temp+"，"+byteImage[i].ToString();
            //    }
            //    System.Diagnostics.Debug.Print(temp);
            //}
            //System.Diagnostics.Debug.Print("=================");

            //byte[] TemFileContent = new byte[1024 * 100];
            byte[] TemFileContent = new byte[512 * 4000 + 100];
            System.Int32 ByteReaded = 0x00;

            aFile = new FileStream("./123456789.bmp", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            FileStream bfile;
            //bfile = new FileStream(image1.GetHbitmap(),FileAccess.Read);
            ByteReaded = aFile.Read(TemFileContent, 0, 54);
            Int32 BMoffset = ((TemFileContent[13] << 24) + (TemFileContent[12] << 16) + (TemFileContent[11] << 8) + TemFileContent[10]);
            HACT_True = ((TemFileContent[19]) << 8) + TemFileContent[18];
            VACT_True = ((TemFileContent[23] << 8) + TemFileContent[22]);



            HACT_Skip = HACT_True;

            try
            { //5a a5 9DF0731A-----提前下个标志位告诉下位机开始送图了，避免特殊图片格式导致错误配置
                TemFileContent[0] = 0xbd; TemFileContent[1] = 0x5a; TemFileContent[2] = 0xa5; TemFileContent[3] = 0x9d; TemFileContent[4] = 0xf0;
                frmHelp.comPort.Write(TemFileContent, 0, 5);
            }
            catch
            {
                MessageBox.Show("串口有误，请检查", "错误");
                return;
            }
            //-----------------------------------
            try
            {
                //HACT_True = Sig_mode.SelectedIndex > 2 ? Convert.ToInt32(2 * ((TemFileContent[19]<<8)+ TemFileContent[18])) : Convert.ToInt32((TemFileContent[19] << 8) + TemFileContent[18]);
                j = 1;
                while (j <= VACT_True)
                {
                    if (HACT_True % 4 != 0)
                        aFile.Seek((VACT_True - j) * (HACT_True * 3 + (HACT_True % 4)) + BMoffset, SeekOrigin.Begin);
                    else
                        aFile.Seek((VACT_True - j) * HACT_True * 3 + BMoffset, SeekOrigin.Begin);

                    ByteReaded = aFile.Read(TemFileContent, 0, HACT_True * 3); // 
                    try
                    {
                        frmHelp.comPort.Write(TemFileContent, 0, HACT_Skip * 3);
                    }
                    catch
                    {
                        MessageBox.Show("串口有误，请检查", "错误");
                        break;
                    }
                    m_txlen += ByteReaded;
                    //  progressBar1.Value = Convert.ToInt32((double)m_txlen / aFile.Length * 100);
                    // label14.Text = progressBar1.Value.ToString() + "%";
                    Application.DoEvents();//重点，必须加上，否则父子窗体都假死
                    j++;
                }
                TemFileContent[0] = 0x5A;
                try
                {
                    frmHelp.comPort.Write(TemFileContent, 0, 1);
                }
                catch
                {
                    MessageBox.Show("串口有误，请检查", "错误");
                    return;
                }
                aFile.Close();
                // File.Delete("./123456789.bmp");
            }
            catch
            {
                MessageBox.Show("unexpected exception occured!");
            }

        }
        //以下未用
        #region
        //未用

        private void RM690B0_Gamma_Load(object sender, EventArgs e)
        {

        }
        private ushort[] gamma_r = new ushort[33];
        private ushort[] gamma_g = new ushort[33];
        private ushort[] gamma_b = new ushort[33];
        private void Rbt_RM690B0_P15_CheckedChanged(object sender, EventArgs e)
        {
            List<NumericUpDown> R_Value = new List<NumericUpDown> { RM690B_R0, RM690B_R1, RM690B_R2, RM690B_R3, RM690B_R4, RM690B_R5, RM690B_R6, RM690B_R7, RM690B_R8, RM690B_R9, RM690B_R10, RM690B_R11, RM690B_R12, RM690B_R13 };
            List<NumericUpDown> G_Value = new List<NumericUpDown> { RM690B_G0, RM690B_G1, RM690B_G2, RM690B_G3, RM690B_G4, RM690B_G5, RM690B_G6, RM690B_G7, RM690B_G8, RM690B_G9, RM690B_G10, RM690B_G11, RM690B_G12, RM690B_G13 };
            List<NumericUpDown> B_Value = new List<NumericUpDown> { RM690B_B0, RM690B_B1, RM690B_B2, RM690B_B3, RM690B_B4, RM690B_B5, RM690B_B6, RM690B_B7, RM690B_B8, RM690B_B9, RM690B_B10, RM690B_B11, RM690B_B12, RM690B_B13 };
            string str = "";
            listBoxB_1.Items.Clear();
            listBoxB_2.Items.Clear();
            listBoxG_1.Items.Clear();
            listBoxG_2.Items.Clear();
            listBoxR_1.Items.Clear();
            listBoxR_2.Items.Clear();
            if (rbt_RM690B0_P27.Checked)
            {
                gamma_r = GAMMAs.IC690B0_Gamma_r;
                gamma_g = GAMMAs.IC690B0_Gamma_g;
                gamma_b = GAMMAs.IC690B0_Gamma_b;
                str = "__GAMMA_SET(0)\r\n"
                        + "TUNING_SPEC(27, 430, 0.300, 0.315, 2.2)\r\n"
                        + "LXY_SPEC(255, 0.001, 0.001, 0.1)\r\n"
                        + "LXY_SPEC(239, 0.001, 0.001, 0.15)\r\n"
                        + "LXY_SPEC(223, 0.001, 0.001, 0.1)\r\n"
                        + "LXY_SPEC(207, 0.001, 0.001, 0.15)\r\n"
                        + "LXY_SPEC(191, 0.001, 0.001, 0.1)\r\n"
                        + "LXY_SPEC(175, 0.001, 0.001, 0.15)\r\n"
                        + "LXY_SPEC(159, 0.001, 0.001, 0.1)\r\n"
                        + "LXY_SPEC(143, 0.001, 0.001, 0.15)\r\n"
                        + "LXY_SPEC(127, 0.001, 0.001, 0.1)\r\n"
                        + "LXY_SPEC(111, 0.001, 0.001, 0.1)\r\n"
                        + "LXY_SPEC(95, 0.001, 0.001, 0.15)\r\n"
                        + "LXY_SPEC(79, 0.001, 0.001, 0.15)\r\n"
                        + "LXY_SPEC(63, 0.001, 0.001, 0.15)\r\n"
                        + "LXY_SPEC(55, 0.001, 0.001, 0.15)\r\n"
                        + "LXY_SPEC(47, 0.001, 0.001, 0.15)\r\n"
                        + "LXY_SPEC(39, 0.001, 0.001, 0.15)\r\n"
                        + "LXY_SPEC(35, 0.001, 0.001, 0.15)\r\n"
                        + "LXY_SPEC(31, 0.001, 0.001, 0.15)\r\n"
                        + "LXY_SPEC(27, 0.001, 0.001, 0.15)\r\n"
                        + "LXY_SPEC(23, 0.001, 0.001, 0.15)\r\n"
                        + "LXY_SPEC(19, 0.001, 0.001, 0.15)\r\n"
                        + "LXY_SPEC(15, 0.001, 0.001, 0.15)\r\n"
                        + "LXY_SPEC(11, 0.001, 0.001, 0.15)\r\n"
                        + "LXY_SPEC(7, 0.001, 0.001, 0.15) \r\n"
                        + "LXY_SPEC(3, 0.001, 0.001, 0.15) \r\n"
                        + "LXY_SPEC(1, 0.001, 0.001, 0.15) \r\n"
                        + "LXY_SPEC(0, 0.001, 0.001, 0.15) \r\n"
                        + "__GAMMA_TUNING                  \r\n"
                        + "SAVE                            \r\n";
                listBoxR_1.Items.AddRange(new string[] { "R0", "R1", "R3", "R7", "R11", "R15", "R19", "R23", "R27", "R31", "R35", "R39", "R47", "R55" });
                listBoxR_2.Items.AddRange(new string[] { "R63", "R79", "R95", "R111", "R127", "R143", "R159", "R175", "R191", "R207", "R223", "R239", "R255" });

                listBoxG_1.Items.AddRange(new string[] { "G0", "G1", "G3", "G7", "G11", "G15", "G19", "G23", "G27", "G31", "G35", "G39", "G47", "G55" });
                listBoxG_2.Items.AddRange(new string[] { "G63", "G79", "G95", "G111", "G127", "G143", "G159", "G175", "G191", "G207", "G223", "G239", "G255" });

                listBoxB_1.Items.AddRange(new string[] { "B0", "B1", "B3", "B7", "B11", "B15", "B19", "B23", "B27", "B31", "B35", "B39", "B47", "B55" });
                listBoxB_2.Items.AddRange(new string[] { "B63", "B79", "B95", "B111", "B127", "B143", "B159", "B175", "B191", "B207", "B223", "B239", "B255" });
                for (int i = 0; i < 14; i++)
                {
                    R_Value[i].Enabled = true;
                    G_Value[i].Enabled = true;
                    B_Value[i].Enabled = true;
                }
            }
            else   //P13
            {
                gamma_r = GAMMAs.IC690B0_Gamma_r_13p;
                gamma_g = GAMMAs.IC690B0_Gamma_g_13p;
                gamma_b = GAMMAs.IC690B0_Gamma_b_13p;

                str = "__GAMMA_SET(0)\r\n"
                        + "TUNING_SPEC(13, 430, 0.300, 0.315, 2.2)\r\n"
                        + "LXY_SPEC(255, 0.001, 0.001, 0.1)\r\n"
                        + "LXY_SPEC(191, 0.001, 0.001, 0.1)\r\n"
                        + "LXY_SPEC(159, 0.001, 0.001, 0.1)\r\n"
                        + "LXY_SPEC(127, 0.001, 0.001, 0.1)\r\n"
                        + "LXY_SPEC(95, 0.001, 0.001, 0.15)\r\n"
                        + "LXY_SPEC(63, 0.001, 0.001, 0.15)\r\n"
                        + "LXY_SPEC(31, 0.001, 0.001, 0.15)\r\n"
                        + "LXY_SPEC(15, 0.001, 0.001, 0.15)\r\n"
                        + "LXY_SPEC(11, 0.001, 0.001, 0.15)\r\n"
                        + "LXY_SPEC(7, 0.001, 0.001, 0.15) \r\n"
                        + "LXY_SPEC(3, 0.001, 0.001, 0.15) \r\n"
                        + "LXY_SPEC(1, 0.001, 0.001, 0.15) \r\n"
                        + "LXY_SPEC(0, 0.001, 0.001, 0.15) \r\n"
                        + "__GAMMA_TUNING                  \r\n"
                        + "SAVE                            \r\n";
                listBoxR_1.Items.AddRange(new string[] { "R0", "R1", "R3", "R7", "R11", "R15", "R31", "R63", "R95", "R127", "R159", "R191", "R255", "XXXX" });
                listBoxR_2.Items.AddRange(new string[] { "XXXX", "XXXX", "XXXX", "XXXX", "XXXX", "XXXX", "XXXX", "XXXX", "XXXX", "XXXX", "XXXX", "XXXX", "XXXX" });
                listBoxG_1.Items.AddRange(new string[] { "G0", "G1", "G3", "G7", "G11", "G15", "G31", "G63", "G95", "G127", "G159", "G191", "G255", "XXXX" });
                listBoxG_2.Items.AddRange(new string[] { "XXXX", "XXXX", "XXXX", "XXXX", "XXXX", "XXXX", "XXXX", "XXXX", "XXXX", "XXXX", "XXXX", "XXXX", "XXXX" });
                listBoxB_1.Items.AddRange(new string[] { "B0", "B1", "B3", "B7", "B11", "B15", "B31", "B63", "B95", "B127", "B159", "B191", "B255", "XXXX" });
                listBoxB_2.Items.AddRange(new string[] { "XXXX", "XXXX", "XXXX", "XXXX", "XXXX", "XXXX", "XXXX", "XXXX", "XXXX", "XXXX", "XXXX", "XXXX", "XXXX" });
                for (int i = 0; i < 14; i++)
                {
                    R_Value[i].Enabled = false;
                    G_Value[i].Enabled = false;
                    B_Value[i].Enabled = false;
                }
            }

            RM690B0_Gamma_SetBox.Text = str;
        }


        //private void Load_GammmPic(string filenames)      //双击 载入 BMP图片
        //{
        //    Int32 HACT_True = 0;
        //    Int32 HACT_Skip = 0;
        //    Int32 VACT_True = 0;
        //    Int32 m_txlen = 0;
        //    Int32 j = 0;
        //    FileStream aFile;

        //    //byte[] TemFileContent = new byte[1024 * 100];
        //    byte[] TemFileContent = new byte[512 * 4000 + 100];
        //    System.Int32 ByteReaded = 0x00;

        //    string FileName = Gamma_loading_path.Text + '\\' + filenames + ".bmp";
        //    aFile = new FileStream(FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
        //    ByteReaded = aFile.Read(TemFileContent, 0, 54);

        //    HACT_True = ((TemFileContent[19]) << 8) + TemFileContent[18];
        //    VACT_True = ((TemFileContent[23] << 8) + TemFileContent[22]);

        //    HACT_Skip = HACT_True;
        //    try
        //    { //5a a5 9DF0731A-----提前下个标志位告诉下位机开始送图了，避免特殊图片格式导致错误配置
        //        TemFileContent[0] = 0xbd; TemFileContent[1] = 0x5a; TemFileContent[2] = 0xa5; TemFileContent[3] = 0x9d; TemFileContent[4] = 0xf0;
        //        frmHelp.comPort.Write(TemFileContent, 0, 5);
        //    }
        //    catch
        //    {
        //        MessageBox.Show("串口有误，请检查", "错误");
        //        return;
        //    }
        //    //-----------------------------------
        //    try
        //    {
        //        j = 1;
        //        aFile.Seek(54, SeekOrigin.Begin);
        //        while (j <= VACT_True)
        //        {
        //            if (HACT_True % 4 != 0)
        //                aFile.Seek((VACT_True - j) * (HACT_True * 3 + (HACT_True % 4)) + 54, SeekOrigin.Begin);
        //            else
        //                aFile.Seek((VACT_True - j) * HACT_True * 3 + 54, SeekOrigin.Begin);

        //            ByteReaded = aFile.Read(TemFileContent, 0, HACT_True * 3); // 
        //            try
        //            {
        //                frmHelp.comPort.Write(TemFileContent, 0, HACT_Skip * 3);
        //            }
        //            catch
        //            {
        //                MessageBox.Show("串口有误，请检查", "错误");
        //                break;
        //            }
        //            m_txlen += ByteReaded;
        //            j++;
        //        }

        //        TemFileContent[0] = 0x5A;
        //        try
        //        {
        //            frmHelp.comPort.Write(TemFileContent, 0, 1);
        //        }
        //        catch
        //        {
        //            MessageBox.Show("串口有误，请检查", "错误");
        //            return;
        //        }
        //        aFile.Close();
        //    }
        //    catch
        //    {
        //        frmHelp.textBox1.Text += "啥图片都没显示";
        //        frmHelp.textBox1.Select(frmHelp.textBox1.Text.Length, 0);
        //        frmHelp.textBox1.ScrollToCaret();
        //    }
        //}
        #endregion

    }
}



